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.
精彩评论