GoHeavyOrGoHome
GoHeavyOrGoHome

Reputation: 273

C#: Manual bit conversion?

Is there a better way to write this than using BitConverter?

public static class ByteArrayExtensions
{

    public static int IntFromUInt24(this byte[] bytes)
    {
        if (bytes == null)
        {
            throw new ArgumentNullException();
        }

        if (bytes.Length != 3)
        {
            throw new ArgumentOutOfRangeException
                ("bytes", "Must have length of three.");
        }

        return BitConverter.ToInt32
                    (new byte[] { bytes[0], bytes[1], bytes[2], 0 }, 0);
    }

}

Upvotes: 1

Views: 449

Answers (1)

CodesInChaos
CodesInChaos

Reputation: 108810

I'd use:

return bytes[2]<<16|bytes[1]<<8|bytes[0];

Be careful with endianness: This code only works with little-endian 24 bit numbers.

BitConverter on the other hand uses native endianness. So your could wouldn't work at all big-endian systems.

Upvotes: 3

Related Questions