开发者

Convert object to byte array in c#

开发者 https://www.devze.com 2023-01-24 23:19 出处:网络
I want to convert object value to byte array in c#. EX: step 1. Input : 2200 step 2. After converting Byte : 0898

I want to convert object value to byte array in c#.

EX:

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

 Output: 开发者_运维技巧08

thanks


You may take a look at the GetBytes method:

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

Also make sure you have taken endianness into consideration in your definition of first byte.


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


Using BitConverter.GetBytes will convert your integer to a byte[] array using the system's native endianness.

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)

If you need explicit control over the endianness of the conversion then you'll need to do it manually:

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)


int number = 2200;
byte[] br = BitConverter.GetBytes(number);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号