简体   繁体   中英

Convert object to byte array in c#

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

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