Take the 2-minute tour ×

I want to convert a given byte array to an int. Then I want to reverse the process. That is I want to get back the original byte array from that int. I thought something like this would have worked:

byte[] myBytes = { 0, 0, 0, 32 };
if (BitConverter.IsLittleEndian)
int i = BitConverter.ToInt32(myBytes, 0);
Console.WriteLine("int: {0}", i); // Output: 32

byte[] newBytes = BitConverter.GetBytes(i);
Console.WriteLine("byte array: " + BitConverter.ToString(newBytes));
// Outputs: 20-00-00-00

So it doesn't give me back the original byte array. What am I doing wrong?

share|improve this question
add comment

1 Answer

You're reversing the bytes with Array.Reverse for no obvious reason - given that you're using BitConverter for both conversion to an int and from an int, you don't need the Array.Reverse call at all.

If you want to treat the byte array as big-endian and you're faced with a little-endian BitConverter, you have to reverse the array in both cases, not just one. Basically you should regard BitConverter as providing a reversible conversion, but it may not be the exact conversion you want.

You might want to use my EndianBitConverter in my MiscUtil project if you want to specify endianness for this kind of conversion.

share|improve this answer
Thank you for your answer. I am not interested about endianess at all, and when i remove the Array.reverse it outputs 00-00-00-20. The original array was 00-00-00-32, so I'm still not getting the original one. Later I will try your EndianBitConverter. –  Jonathan May 5 '13 at 12:06
@Jonathan: No, the original array was effectively "00-00-00-20", because BitConverter.ToString formats it in hex, whereas you're using a decimal literal in the array initializer. Put Console.WriteLine("byte array: " + BitConverter.ToString(myBytes)); to start with and you'll see what I mean. –  Jon Skeet May 5 '13 at 12:08
Yes I see now, BitConverter.ToString was confusing me. Thank you for your help! –  Jonathan May 5 '13 at 12:17
add comment

Your Answer


