[英]C#: Manual bit conversion?
有沒有比使用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);
}
}
我會用:
return bytes[2]<<16|bytes[1]<<8|bytes[0];
注意字節序:此代碼僅適用於低字節序的24位數字。
另一方面,BitConverter使用本機字節序。 因此,您將無法在所有大端系統上工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.