簡體   English   中英

C#:手動位轉換?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM