Sebastien Guimmara
Sebastien Guimmara

Reputation: 175

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 ?

Upvotes: 1

Views: 3111

Answers (2)

Rox
Rox

Reputation: 161

First solution proposed by Stanley fails when the Int16 value is negative. See shifting the sign bit in .Net for an explanation.

The proper implementation should be

private Int16 SwitchEndianness(Int16 i)
{
    return (Int16)((i << 8) + ((UInt16)i >> 8));
}

Upvotes: 1

D Stanley
D Stanley

Reputation: 152654

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.

Upvotes: 4

Related Questions