int i =5;
byte j[2];
上記は私が持っているものです。5 を 16 進数の 0x35 に等しくしたいのですが、これは ASCII では '5' です。そのように変換するにはどうすればよいj[0]= i = 0x35
ですか?
int i =5;
byte j[2];
上記は私が持っているものです。5 を 16 進数の 0x35 に等しくしたいのですが、これは ASCII では '5' です。そのように変換するにはどうすればよいj[0]= i = 0x35
ですか?
Google クエリに「ascii」と入力して最初のヒットを取得すると、数字のオフセットが 48 であることがわかります。
やや面倒ですが、常に正しい方法は、 Encoding クラスを使用することです。
byte[] j = Encoding.ASCII.GetBytes(i.ToString());
これにより、適切な結果である長さ 1 の配列が得られます。
そのためにchar/int演算を使用できます
j[2] = '0' + (byte)i;
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
).
単純に追加0x30
してi
、結果をbyte
再度キャストします。
j[0] = (byte)(i + 0x30);
これを使って:
j[0] = (byte)('0' + i);
これにより、i が 0 の場合は i だけになり、i が増加するたびにそれも増加します。
も使用できますchar
。関連する問題を解決しました。
char A = 'A';
char B = A++;