Convert an object to a byte array in C #

I want to convert the value of an object to an array of bytes in C #.

Example:

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

thanks

+6
c # bytearray
source share
4 answers

You can 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 that you accept endianness in your first byte definition.

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

Using BitConverter.GetBytes , you will convert your integer into a byte[] array using the internal system entity.

 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 conversion content, you need to do this 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) 
+4
source share
 int number = 2200; byte[] br = BitConverter.GetBytes(number); 
+1
source share

All Articles