Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# byte[] to long and back

Tags:

arrays

c#

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)
    Array.Reverse(myBytes);
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?

like image 358
Jonathan Avatar asked Oct 16 '25 10:10

Jonathan


1 Answers

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.

like image 67
Jon Skeet Avatar answered Oct 18 '25 23:10

Jon Skeet