How to get little endian data from big endian in c# using bitConverter.ToInt32 method?

Dany picture Dany · Nov 23, 2011 · Viewed 61.8k times · Source

I am making application in C# which has a byte array containing hex values.

I am getting data as a big-endian but I want it as a little-endian and I am using Bitconverter.toInt32 method for converting that value to integer.

My problem is that before converting the value, I have to copy that 4 byte data into temporary array from source byte array and then reverse that temporary byte array.

I can't reverse source array because it also contains other data.

Because of that my application becomes slow.

In the code I have one source array of byte as waveData[] which contains a lot of data.

byte[] tempForTimestamp=new byte[4];
tempForTimestamp[0] = waveData[290];
tempForTimestamp[1] = waveData[289];
tempForTimestamp[2] = waveData[288];
tempForTimestamp[3] = waveData[287];
int number = BitConverter.ToInt32(tempForTimestamp, 0);

Is there any other method for that conversion?

Answer

Allison A picture Allison A · Mar 18, 2013

In modern-day Linq the one-liner and easiest to understand version would be:

int number = BitConverter.ToInt32(waveData.Skip(286).Take(4).Reverse().ToArray(), 0);

You could also...

byte[] tempForTimestamp = new byte[4];
Array.Copy(waveData, 287, tempForTimestamp, 0, 4);
Array.Reverse(tempForTimestamp);
int number = BitConverter.ToInt32(tempForTimestamp);

:)