简体   繁体   中英

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);
    }

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM