[英]C#: Manual bit conversion?
Is there a better way to write this than using BitConverter
? 有没有比使用
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. 注意字节序:此代码仅适用于低字节序的24位数字。
BitConverter on the other hand uses native endianness. 另一方面,BitConverter使用本机字节序。 So your could wouldn't work at all big-endian systems.
因此,您将无法在所有大端系统上工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.