我有一个文本文件中的数据列表,它以十六进制编写,如下所示:
AE 66 55 78 FF 6A 48 40 CA BC 1B 2C 18 94 28 28
CF EA 02 00 02 51 23 05 0E F2 DD 5A E5 38 48 48
CA BC 1B 2C 18 94 28 40 EE B6 65 87 E3 6A 48 48
..
我想将值转换为另一个文本文件中的char
我在c#中试过这个:
private static void OpenFile()
{
ASCIIEncoding ascii = new ASCIIEncoding();
string str = string.Empty;
using (System.IO.BinaryReader br = new System.IO.BinaryReader
(new System.IO.FileStream(
"hexa2.txt",
System.IO.FileMode.Open,
System.IO.FileAccess.Read,
System.IO.FileShare.None), Encoding.UTF8))
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("sms23.txt"))
{
str = @"the path";
Byte[] bytes = ascii.GetBytes(str);
foreach (var value in bytes)
sw.WriteLine("{0:X2}", value);
sw.WriteLine();
String decoded = ascii.GetString(bytes);
sw.WriteLine("Decoded string: '{0}'", decoded);
}
}
我希望每个字节都会转换为char。例如“EE”是“î”
您有一个文本文件,而不是二进制文件,因此您必须读取十六进制字符串,然后转换为相应的数字,然后获取该数字的相应字符。
// string input = @"EE B6 45 78 FF 6A 48 40 CA BC 1B 2C 18 94 28 28
// CF EA 02 00 00 00 00 00 0E F2 DD 5A E4 38 48 48
// CA BC 1B 2C 18 94 28 40 EE B6 45 78 FF 6A 48 48 ";
string input = File.ReadAllText("yourFile.txt");
string output = new string(
input.Replace("\n"," ").Replace("\r","")
.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries)
.Select(x=>(char)Convert.ToInt32(x,16))
.ToArray()
);
File.WriteAllText("newFile.txt",output);
//Output: î¶ExÿjH@ʼ←,↑?((Ïê☻ ♫òÝZä8HHʼ←,↑?(@î¶ExÿjHH
你没有指定编码,所以我只是直接将十六进制转换为char。要指定编码,您应使用以下代码
byte[] dataArray =
input.Replace("\n"," ").Replace("\r","")
.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries)
.Select(x=>(byte)Convert.ToInt32(x,16))
.ToArray();
string output = Encoding.UTF8.GetString(dataArray);
在哪里可以替换所需的Encoding.UTF8
。
string hex = File.ReadAllText("file.txt").Replace(" ","").Replace(Environment.NewLine,"");
var result = Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
File.WriteAllBytes( "file.bin", result);