问题描述
我有以下代码:
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字节
The FILE_PATH is a const string that contains the path to the binary file being read.The binary file is a mixture of integers and characters.The integers are 1 bytes each and each character is written to the file as 2 bytes.
例如,该文件具有以下数据:
For example, the file has the following data :
1HELLO HOW ARE YOU45YOU正在寻找伟大//等等
1HELLO HOW ARE YOU45YOU ARE LOOKING GREAT //and so on
请注意:每个整数与串相关它后面的字符。所以1与HELLO HOW ARE YOU和45你看起来棒极了等相关联。
Please note: Each integer is associated with the string of characters following it. So 1 is associated with "HELLO HOW ARE YOU" and 45 with "YOU ARE LOOKING GREAT" and so on.
现在二进制写入(我不知道为什么但我有这个活),使得'1'将只需要1个字节,而H(和其他字符)都需要2个字节。
Now the binary is written (I do not know why but I have to live with this) such that '1' will take only 1 byte while 'H' (and other characters) take 2 bytes each.
因此,这里是什么文件实际上包含:
So here is what the file actually contains:
0100480045..and等
继承人的细分:
0100480045..and so onHeres the breakdown:
01是整数1
0048的第一个字节是H的2个字节(H为十六进制48)
0045是'E'的2个字节(E =×45)
01 is the first byte for the integer 10048 are the 2 bytes for 'H' (H is 48 in Hex)0045 are the 2 bytes for 'E' (E = 0x45)
等..
我希望我的控制台打印可读的格式将此文件的:那我希望它打印出1 HELLO HOW ARE YOU,然后45你正在寻找伟大等等...
and so on..I want my Console to print human readable format out of this file: That I want it to print "1 HELLO HOW ARE YOU" and then "45 YOU ARE LOOKING GREAT" and so on...
时我在做什么正确的?是否有一个更简单的/有效的方法?
我行Console.WriteLine(Convert.ToString(B [POS]));什么也不做,但打印整数值,而不是实际的字符我想要的。这是文件中的整数确定的,但那我怎么读出来的字符?
Is what I am doing correct? Is there an easier/efficient way? My line Console.WriteLine(Convert.ToString(b[pos])); does nothing but prints the integer value and not the actual character I want. It is OK for integers in the file but then how do I read out characters?
任何帮助将非常感激。
谢谢
Any help would be much appreciated.Thanks
推荐答案
我想你要找的是的。
由于您的字符串数据由2字节字符,你怎么可以让你的字符串的是:
Since your string data is composed of 2 byte characters, how you can get your string out is:
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++;
}
}
这篇关于从byte []转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!