LoginSignup
2
2

More than 5 years have passed since last update.

Encoding.ASCII.GetString(byte[])の結果に'?'(0x3F)が混ざる

Last updated at Posted at 2015-08-20

Encoding.ASCII.GetStringに与えるbyte配列の中にASCII範囲外の値(つまり0x00~0x7F以外)が入っていた場合、そのbyteは'?'(=0x3F)に変換されるようです。
つまり不可逆変換となります。

byte[] arr1 = { 0x30, 0x39, 0x41, 0x5A, 0xAA };
string str = Encoding.ASCII.GetString(byte);
byte[] arr2 = Encoding.ASCII.GetBytes(str);     // 逆変換

結果:
arr1 : { 0x30, 0x39, 0x41, 0x5A, 0xAA }
arr2 : { 0x30, 0x39, 0x41, 0x5A, 0x3F }

対策について追記(2015/08/24)
コメントで指摘いただいた、「ISO-8859-1」によるエンコーディングを行った結果、望む結果を得ることができました。

対策例
byte[] arr1 = { 0x30, 0x39, 0x41, 0x5A, 0xAA };
string str = Encoding.GetEncoding("ISO-8859-1").GetString(byte);
byte[] arr2 = Encoding.GetEncoding("ISO-8859-1").GetBytes(str);     // 逆変換

結果:
arr1 : { 0x30, 0x39, 0x41, 0x5A, 0xAA }
arr2 : { 0x30, 0x39, 0x41, 0x5A, 0xAA }

( @yuba さん、ありがとうございました )

2
2
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2