How to Get Little Endian Data from Big Endian in C# Using Bitconverter.Toint32 Method

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

If you know the data is big-endian, perhaps just do it manually:

int value = (buffer[i++] << 24) | (buffer[i++] << 16)
| (buffer[i++] << 8) | buffer[i++];

this will work reliably on any CPU, too. Note i is your current offset into the buffer.

Another approach would be to shuffle the array:

byte tmp = buffer[i+3];
buffer[i+3] = buffer[i];
buffer[i] = tmp;
tmp = buffer[i+2];
buffer[i+2] = buffer[i+1];
buffer[i+1] = tmp;
int value = BitConverter.ToInt32(buffer, i);
i += 4;

I find the first immensely more readable, and there are no branches / complex code, so it should work pretty fast too. The second could also run into problems on some platforms (where the CPU is already running big-endian).

Converting Big endian to Little endian in C#

Take a look at the BitConverter

First you check if your system is little endian or not and then reverse the bytes depending on that.

float num = 1.2f;

if (!BitConverter.IsLittleEndian)
{
byte[] bytes = BitConverter.GetBytes(num);
Array.Reverse(bytes, 0, bytes.Length);

num = BitConverter.ToSingle(bytes, 0);
}

Console.WriteLine(num);

64Bit Big Endian data from ushort array

Your first code snippet should actually shift by 16 bits, not 32, if command.Data really is a ushort[] array.

uint bigEndian32 = ((uint)command.Data[0] << 16) | command.Data[1];

For 64-bit, you'd just keep shifting left by 16 bits more each time:

ulong bigEndian64 = ((ulong)command.Data[0] << 48) | (command.Data[1] << 32) | (command.Data[2] << 16) | command.Data[3];

Conversion to little endian format in C

#define BS16(x) (((x) >> 8) | ((x) << 8))
int main(void)
{
uint16_t arr[] = {0x1122, 0x2233, 0xaabb};
printf("%hx %hx %hx\n", BS16(arr[0]), BS16(arr[1]), BS16(arr[2]));
arr[0] = BS16(arr[0]);
}

Efficient way to read big endian data in C#

BitConverter.ToInt32 isn't very fast in the first place. I'd simply use

public static int ToInt32BigEndian(byte[] buf, int i)
{
return (buf[i]<<24) | (buf[i+1]<<16) | (buf[i+2]<<8) | buf[i+3];
}

You could also consider reading more than 4 bytes at a time.

C# little endian or big endian?

C# itself doesn't define the endianness. Whenever you convert to bytes, however, you're making a choice. The BitConverter class has an IsLittleEndian field to tell you how it will behave, but it doesn't give the choice. The same goes for BinaryReader/BinaryWriter.

My MiscUtil library has an EndianBitConverter class which allows you to define the endianness; there are similar equivalents for BinaryReader/Writer. No online usage guide I'm afraid, but they're trivial :)

(EndianBitConverter also has a piece of functionality which isn't present in the normal BitConverter, which is to do conversions in-place in a byte array.)



Related Topics



Leave a reply



Submit