开发者

C#: Manual bit conversion?

开发者 https://www.devze.com 2023-01-20 00:44 出处:网络
Is there a better way to write this than using BitConverter? public static class ByteArrayExtensions { public static int IntFromUInt24(this byte[] bytes)

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 BitConverte开发者_Python百科r.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.

0

精彩评论

暂无评论...
验证码 换一张
取 消