6

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

1
  • possible duplicate of Int to byte array Commented Nov 15, 2010 at 14:53

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

4

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)

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.