Search code examples
c#.netbinarybit-manipulationendianness

How to swap endianness of Int16 without BitConverter


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 ?


Solution

  • 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.