[英]Converting from byte[] to 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是十六進制的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 []數組並生成一個字符串。
請注意,這與將byte []數組中的字節盲目地復制到大塊內存並將其稱為字符串不同。 例如,GetString()方法必須驗證字節並禁止無效的代理。
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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.