簡體   English   中英

如何讀取字節數組中的單個BIT?

[英]How to read a single BIT in an Array of Bytes?

問題是我有一個帶有200個索引的Byte數組,只想檢查MyArray [75]的第四位是零(0)還是一(1)。

byte[] MyArray; //with 200 elements

//check the fourth BIT of  MyArray[75]

元素75中的第四位?

if((MyArray[75] & 8) > 0) // bit is on
else // bit is off

&運算符允許您使用值作為掩碼。

xxxxxxxx = ?
00001000 = 8 &
----------------
0000?000 = 0 | 8

您可以使用此方法使用相同的技術收集任何位值。

1   = 00000001
2   = 00000010
4   = 00000100
8   = 00001000
16  = 00010000
32  = 00100000
64  = 01000000
128 = 10000000

就像是:

if ( (MyArray[75] & (1 << 3)) != 0)
{
   // it was a 1
}

假設你的意思是右邊的第4位。

你可能想看看System.Collections.BitArray ,只是為了確保你沒有重新發明輪子。

    private bool BitCheck(byte b, int pos)
    {
        return (b & (1 << (pos-1))) > 0;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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