如何读取字节数组中的单个BIT?

mam*_*ius 3 .net c# arrays byte bit

问题是我有一个带有200个索引的Byte数组,只想检查MyArray [75]的第四位是零(0)还是一(1).

byte[] MyArray; //with 200 elements

//check the fourth BIT of  MyArray[75]
Run Code Online (Sandbox Code Playgroud)

Spe*_*ort 8

元素75中的第四位?

if((MyArray[75] & 8) > 0) // bit is on
else // bit is off
Run Code Online (Sandbox Code Playgroud)

&运算符允许您使用值作为掩码.

xxxxxxxx = ?
00001000 = 8 &
----------------
0000?000 = 0 | 8
Run Code Online (Sandbox Code Playgroud)

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

1   = 00000001
2   = 00000010
4   = 00000100
8   = 00001000
16  = 00010000
32  = 00100000
64  = 01000000
128 = 10000000
Run Code Online (Sandbox Code Playgroud)