从byte 转换为string

我有以下代码:

using (BinaryReader br = new BinaryReader( File.Open(FILE_PATH, FileMode.Open, FileAccess.ReadWrite))) { int pos = 0; int length = (int) br.BaseStream.Length; while (pos < length) { b[pos] = br.ReadByte(); pos++; } pos = 0; while (pos < length) { Console.WriteLine(Convert.ToString(b[pos])); pos++; } } 

FILE_PATH是一个const字符串,包含要读取的二进制文件的路径。 二进制文件是整数和字符的混合。 整数每个1个字节,每个字符作为2个字节写入文件。

例如,该文件包含以下数据:

1HELLO你是如何看待你的//等等

请注意:每个整数都与其后面的字符串相关联。 所以1与“HELLO HOW ARE YOU”有关,45与“你看起来很棒”等等有关。

现在编写了二进制文件(我不知道为什么,但我必须忍受这个),这样“1”只需要1个字节,而“H”(和其他字符)每个需要2个字节。

所以这是文件实际包含的内容:

0100480045 ……依此类推:

01是整数1的第一个字节0048是’H’的2个字节(H是hex的48)0045是’E’的2个字节(E = 0x45)

我希望我的控制台能够从这个文件中打印出人类可读的格式:我希望它打印出“1你好如何”,然后“45你看起来很棒”等等……

我正在做的是正确的吗? 有更简单/有效的方法吗? 我的行Console.WriteLine(Convert.ToString(b [pos])); 什么都不做,但打印整数值,而不是我想要的实际字符。 对于文件中的整数是可以的,但是我如何读出字符呢?

任何帮助将非常感激。 谢谢

我认为你要找的是Encoding.GetString 。

由于您的字符串数据由2个字节的字符组成,因此如何将字符串输出为:

 for (int i = 0; i < b.Length; i++) { byte curByte = b[i]; // Assuming that the first byte of a 2-byte character sequence will be 0 if (curByte != 0) { // This is a 1 byte number Console.WriteLine(Convert.ToString(curByte)); } else { // This is a 2 byte character. Print it out. Console.WriteLine(Encoding.Unicode.GetString(b, i, 2)); // We consumed the next character as well, no need to deal with it // in the next round of the loop. i++; } } 

您可以使用String System.Text.UnicodeEncoding.GetString(),它接受byte []数组并生成一个字符串。 我发现这个链接非常有用

 using (BinaryReader br = new BinaryReader(File.Open(FILE_PATH, FileMode.Open, FileAccess.ReadWrite))) { int length = (int)br.BaseStream.Length; byte[] buffer = new byte[length * 2]; int bufferPosition = 0; while (pos < length) { byte b = br.ReadByte(); if(b < 10) { buffer[bufferPosition] = 0; buffer[bufferPosition + 1] = b + 0x30; pos++; } else { buffer[bufferPosition] = b; buffer[bufferPosition + 1] = br.ReadByte(); pos += 2; } bufferPosition += 2; } Console.WriteLine(System.Text.Encoding.Unicode.GetString(buffer, 0, bufferPosition)); 

}