A quick way to swap bytes in an array from big endian to little endian in C #

I am reading from a binary stream that is big-endian. The BitConverter class does this automatically. Unfortunately, the floating point conversion is no different to me from BitConverter.ToSingle (byte []), so I have my own routine from an employee. But the input byte [] must be in little-endian style. Does anyone have a quick way to convert the endianness of a byte [] array. Of course, I could change every byte, but there should be a trick. Thanks.

+5
source share
3 answers

I am using LINQ:

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

.Skip() .Take() BitConverter.

+4

endianess :

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++;
    }
  }
}
+3

What does the routine look like from your colleague? If it explicitly refers to bytes, you can change the code (or, more precisely, create a separate method for data in big-endian format) instead of changing the bytes.

0
source