I need to read binary files containing millions of Int16 stored as big endian.
My first method was to use BitConverter and Array.Reverse() but that appears too slow for my purpose. Is there a way to do it with bitwise arithmetic instead ?
Well the math for an Int16
would just be:
public Int16 SwitchEndianness(Int16 i)
{
return (Int16)((i << 8) + (i >> 8));
}
or if you have a 2-byte array:
public Int16 SwitchEndianness(byte[] a)
{
//TODO: verify length
return (Int16)((a[0] << 8) + a[1]);
}
but you'll have to try it and see if it's faster than reversing the array.