我有以下代码:

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你好吗45你看起来很棒//等等

请注意:每个整数都与之后的字符字符串关联。因此,1与“你好”和“你看起来很棒”等45相关联,依此类推。

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

因此,这是该文件实际包含的内容:

0100480045..等等,因此崩溃:

01是整数1 0048的第一个字节是“ H”的2个字节(HEX中的H 48)0045是'e'的2个字节(e = 0x45)

依此类推。.我希望我的控制台从此文件中打印出人类可读格式:我希望它打印出“ 1个你好,你好吗”,然后“ 45你看起来很棒”等等...

我做的正确吗?有一种更简单/有效的方法吗?我的行控制台(convert.tostring(b [pos]));除了打印整数价值,而不是我想要的实际字符。文件中的整数还可以,但是如何读取字符?

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

有帮助吗?

解决方案

我认为您正在寻找的是 encoding.getString.

由于您的字符串数据由两个字节字符组成,因此如何将字符串删除是:

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.unicodeCoding.getString(),该数个字节[]数组并产生字符串。

我发现这个链接非常有用

请注意,这与将字节[]数组中的字节复制到内存的大块并将其称为字符串的情况不同。例如,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归因
不隶属于 StackOverflow
scroll top