-2
int i =5;
byte j[2];

上記は私が持っているものです。5 を 16 進数の 0x35 に等しくしたいのですが、これは ASCII では '5' です。そのように変換するにはどうすればよいj[0]= i = 0x35 ですか?

4

6 に答える 6

1

Google クエリに「ascii」と入力して最初のヒットを取得すると、数字のオフセットが 48 であることがわかります。

やや面倒ですが、常に正しい方法は、 Encoding クラスを使用することです。

 byte[] j = Encoding.ASCII.GetBytes(i.ToString());

これにより、適切な結果である長さ 1 の配列が得られます。

于 2012-10-05T10:51:46.303 に答える
0

そのためにchar/int演算を使用できます

j[2] = '0' + (byte)i;
于 2012-10-05T10:41:56.733 に答える
0

Since .NET doesn’t use ASCII for its string encoding, the “proper” way of doing this is a bit roundabout:

byte[] result = Encoding.ASCII.GetBytes(i.ToString());

(This needs to have the System.Text namespace imported.)

Since the ASCII encoding is pretty straightforward (i.e. corresponds to .NET’s internal character encoding for the first 127 code points) you can also cheat and use the method proposed in the other answers (i.e. either add '0' or 0x30 and explicitly convert to byte).

于 2012-10-05T10:49:51.273 に答える
0

単純に追加0x30してi、結果をbyte再度キャストします。

j[0] = (byte)(i + 0x30);
于 2012-10-05T10:39:26.270 に答える
0

これを使って:

j[0] = (byte)('0' + i);

これにより、i が 0 の場合は i だけになり、i が増加するたびにそれも増加します。

于 2012-10-05T10:45:20.853 に答える
0

も使用できますchar。関連する問題を解決しました。

char A = 'A';
char B = A++;
于 2017-02-27T17:33:20.803 に答える