2010-11-15 106 views
6

我想将对象值转换为C#中的字节数组。将对象转换为C中的字节数组#

EX:

step 1. Input : 2200 
step 2. After converting Byte : 0898 
step 3. take first byte(08) 

Output: 08 

感谢

+0

[INT要字节数组]的可能重复(HTTP:/ /stackoverflow.com/questions/4176653/int-to-byte-array) – Ani 2010-11-15 14:53:39

回答

11

你可以看看的GetBytes方法:

int i = 2200; 
byte[] bytes = BitConverter.GetBytes(i); 
Console.WriteLine(bytes[0].ToString("x")); 
Console.WriteLine(bytes[1].ToString("x")); 

另外,还要确保你已经采取endianness考虑在你的定义第一个字节

4
byte[] bytes = BitConverter.GetBytes(2200); 
Console.WriteLine(bytes[0]); 
4

使用BitConverter.GetBytes将使用系统的本地字节序将您的整数转换为byte[]数组。

short s = 2200; 
byte[] b = BitConverter.GetBytes(s); 

Console.WriteLine(b[0].ToString("X")); // 98 (on my current system) 
Console.WriteLine(b[1].ToString("X")); // 08 (on my current system) 

如果你需要转换的字节顺序明确的控制,那么你就需要手动做到这一点:

short s = 2200; 
byte[] b = new byte[] { (byte)(s >> 8), (byte)s }; 

Console.WriteLine(b[0].ToString("X")); // 08 (always) 
Console.WriteLine(b[1].ToString("X")); // 98 (always) 
1
int number = 2200; 
byte[] br = BitConverter.GetBytes(number); 
相关问题