如何将十六进制数据从文本文件转换为字符串文件

时间:2019-03-25 12:53:48

标签: c# hex

我在文本文件中有一个数据列表,它以十六进制形式写成这样:

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”是“î”

2 个答案:

答案 0 :(得分:1)

您有一个文本文件,而不是二进制文件,因此您必须阅读十六进制字符串,然后将其转换为相应的数字,然后获取该数字的相应字符。

// 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替换为所需的

答案 1 :(得分:0)

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);