在C#中将对象转换为字节数组

6
我希望你能帮我将C#中的对象值转换为字节数组。
示例:
 step 1. Input : 2200
 step 2. After converting Byte : 0898
 step 3. take first byte(08)

 Output: 08

谢谢


可能是[Int to byte array]的重复问题(https://dev59.com/Rm855IYBdhLWcg3wuG-W)。 - Ani
4个回答

10

您可以查看 GetBytes 方法:

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

还要确保在定义第一个字节时考虑了字节序


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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接