我有以下代码:
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 是一个常量字符串,包含正在读取的二进制文件的路径。 二进制文件是整数和字符的混合体。 每个整数都是 1 个字节,每个字符作为 2 个字节写入文件。
例如,文件有以下数据:
1HELLO HOW ARE YOU45YOU ARE LOOKING GREAT//等等
请注意:每个整数都与其后面的字符串相关联。因此 1 与“HELLO HOW ARE YOU”相关,45 与“你看起来很棒”等等。
现在二进制文件是这样写的(我不知道为什么,但我不得不接受)这样“1”只占用 1 个字节,而“H”(和其他字符)每个占用 2 个字节。
所以这里是文件实际包含的内容:
0100480045..等等 细目如下:
01 是整数 1 的第一个字节 0048 是 'H' 的 2 个字节(H 在十六进制中是 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++;
}
}
关于c# - 从 byte[] 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1309003/