1

有没有比使用更好的方法来写这个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);
    }

}
4

1 回答 1

3

我会使用:

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

注意字节顺序:此代码仅适用于 little-endian 24 位数字。

另一方面,BitConverter 使用本机字节序。所以你的可能在所有大端系统中都不起作用。

于 2010-10-15T21:54:12.307 回答