質問

次のコードがあります。

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は「Hello How Are You」に関連付けられ、45は「あなたは見栄えが良い」などに関連付けられています。

これで、バイナリは書かれています(理由はわかりませんが、これと一緒に暮らす必要があります)。「1」は「H」(および他の文字)がそれぞれ2バイトを取る間、1バイトしか取るようにします。

ファイルが実際に含むものは次のとおりです。

0100480045 ..そして、故障するのは次のとおりです。

01は整数の最初のバイトです1 0048は「h」の2バイトです(hは16進数で48です)0045は「e」の2バイトです(e = 0x45)

など..コンソールにこのファイルから人間の読み取り可能な形式を印刷してもらいたい:「1 Hello How Are You」を印刷したいのですが、「45あなたは見栄えが良い」など...

私がしていることは正しいですか?より簡単/効率的な方法はありますか? My Line Console.WriteLine(Convert.ToString(B [POS]));私が望む実際のキャラクターではなく、整数値を印刷する以外に何もしません。ファイル内の整数では問題ありませんが、キャラクターを読み出すにはどうすればよいですか?

どんな助けも大歓迎です。ありがとう

役に立ちましたか?

解決

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

}

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top