Converting from byte[] to string

不羁岁月 提交于 2019-12-01 21:16:08

I think what you are looking for is Encoding.GetString.

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++;
  }
}

You can use String System.Text.UnicodeEncoding.GetString() which takes a byte[] array and produces a string.

I found this link very useful

Note that this is not the same as just blindly copying the bytes from the byte[] array into a hunk of memory and calling it a string. The GetString() method must validate the bytes and forbid invalid surrogates, for example.

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));

}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!