简体   繁体   中英

How can I convert a number's digits into ASCII bytes?

如果我有int x = 24 ,如何将其转换为2字节数组,其中第一个字节存储250 )的值,第二个字节存储452 )的值?

System.Text.Encoding.ASCIIEncoding.GetBytes(x.ToString());

最简单的方法是先转换为String,然后将其转换为字节。

byte[] bytes = System.Text.Encoding.ASCII.GetBytes(x.ToString());

您可以使用除法和模运算符:

byte[] data = new byte[] { (byte)(48 + x / 10), (byte)(48 + x % 10) };
int x_int = 24;
string x_string = x_int.ToString();
var x_bytes = (from x in x_string select Convert.ToByte(x)).ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM