Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to swap bytes in array from big endian to little endian in C#

Tags:

c#

endianness

I'm reading from a binary stream which is big-endian. The BitConverter class does this automatically. Unfortunately, the floating point conversion I need is not the same as BitConverter.ToSingle(byte[]) so I have my own routine from a co-worker. But the input byte[] needs to be in little-endian. Does anyone have a fast way to convert endianness of a byte[] array. Sure, I could swap each byte but there has got to be a trick. Thanks.

like image 217
initialZero Avatar asked Oct 21 '09 20:10

initialZero


People also ask

How do you convert big endian to little endian?

This C# program is used to convert big endian to little endian. We have defined the value of 'little' variable as 2777. The BitConverter is used to convert the given integer value to bytes and reverse the value using Reverse() function.

Is there a quick way to determine endianness of your machine?

Is there a quick way to determine endianness of your machine? There are n no. of ways for determining endianness of your machine.

What is little endian byte swap?

In little-endian style, the bytes are written from left to right in increasing significance. In big-endian style, the bytes are written from left to right in decreasing significance. The swapbytes function swaps the byte ordering in memory, converting little endian to big endian (and vice versa).

Does endianness affect bit order?

Bit order usually follows the same endianness as the byte order for a given computer system. That is, in a big endian system the most significant bit is stored at the lowest bit address; in a little endian system, the least significant bit is stored at the lowest bit address.


2 Answers

Here is a fast method for changing endianess for singles in a byte array:

public static unsafe void SwapSingles(byte[] data) {
  int cnt = data.Length / 4;
  fixed (byte* d = data) {
    byte* p = d;
    while (cnt-- > 0) {
      byte a = *p;
      p++;
      byte b = *p;
      *p = *(p + 1);
      p++;
      *p = b;
      p++;
      *(p - 3) = *p;
      *p = a;
      p++;
    }
  }
}
like image 130
Guffa Avatar answered Sep 21 '22 22:09

Guffa


I use LINQ:

var bytes = new byte[] {0, 0, 0, 1};
var littleEndianBytes = bytes.Reverse().ToArray();
Single x = BitConverter.ToSingle(littleEndianBytes, 0);

You can also .Skip() and .Take() to your heart's content, or else use an index in the BitConverter methods.

like image 26
Pat Avatar answered Sep 21 '22 22:09

Pat