字节右移
field
表示您从右侧 (LSB) 获得的字的位数。byte = byte >> field
会将field
字节的位数带到byte
LSB 位置。然后byte = byte & 0x01
与字节相加,0x01
这意味着1
如果它最初在位号中设置了位,则结果将在 LSB 中field
包含 a,或者0
如果在该位置清除了该位,则结果将包含 a。
例如,需要检查字节0x52
是否设置了位号的测试4
如下所示。
byte = 0x52 = 0 1 0 1 0 0 1 0
field = 0x04 = 0 0 0 0 0 1 0 0
Operation: byte = byte >> field
The bit number 4 is single quoted below. Note how it moves
intermediate byte | lost bits during
states | right shifting
byte = 0x52 = 0 1 0 '1' 0 0 1 0 |
shift 1 = 0x29 = 0 0 1 0 '1' 0 0 1 | 0
shift 2 = 0x14 = 0 0 0 1 0 '1' 0 0 | 1 0
shift 3 = 0x0A = 0 0 0 0 1 0 '1' 0 | 0 1 0
shift 4 = 0x05 = 0 0 0 0 0 1 0 '1' | 0 0 1 0
Note that the bit 4 is now moved at the LSB/righ most position of the byte
now if we test the rightmost position of the above byte then we can check
if the bit number 4 had its bit set or cleared, with the following operation
Operation: byte = byte & 0x01
byte is now 0x05
byte = 0x05 = 0 0 0 0 0 1 0 '1'
AND & & & & & & & &
0x01 = 0 0 0 0 0 0 0 1
---- ----------------
0x01 0 0 0 0 0 0 0 1
Now byte contains 0x01 so bit number 4 had the bit set. In the other case the
final answer would be 0.
但是我们无法检查byte & field
编号的位field
是否设置或清除。这是因为field
它只是一个二进制文件而不是掩码。如果我们这样做byte & field
了,就会发生以下情况。
byte = 0x52 = 0 1 0 1 0 0 1 0
AND & & & & & & & &
field = 0x04 = 0 0 0 0 0 1 0 0
---- ---------------
0x00 0 0 0 0 0 0 0 0
具有field
值0x04
,即其位号2
集。通过这个操作,我们实际检查了是否设置了位数2
。如果 的 值field
是5
位0
, 并且2
将被设置,那么如果提取位的状态0
和2
的 值,则直接与上面类似的结果将导致byte
,这可以采用四种可能的组合。
将 0x01 向左移动并制作掩码
测试 a 的位值的其他方法byte
不是将其byte
自身移动,而是将0x01
掩码field
时间向左移动,并将其与字节进行 AND 运算,并检查是否为零。(byte & (0x01 << field)) != 0
设置编号位时为真,field
否则为假。
Operation: (0x01 << field)
Shifting 0x01 to the left field times field = 0x04 for the example
= 0x01 = 0 0 0 0 0 0 0 1
shift 1 = 0x02 = 0 0 0 0 0 0 1 0
shift 2 = 0x04 = 0 0 0 0 0 1 0 0
shift 3 = 0x08 = 0 0 0 0 1 0 0 0
shift 4 = 0x10 = 0 0 0 1 0 0 0 0
After the left shift the '1' moves in the bit position 4
Now we AND this with the byte to check if the bit position 4
is set or clear.
byte = 0x52 = 0 1 0 1 0 0 1 0
AND & & & & & & & &
(0x01 << field) = 0x10 = 0 0 0 1 0 0 0 0
---- ---------------
0x10 0 0 0 1 0 0 0 0
Therefore the answer (0x01 != 0) is 1 there fore the bit 4 is set. It the bit 4
was not set then the answer would be 0.
使用预先计算的掩码
如果您有一个需要定期测试的特定格式的字节,例如某个预定义字的某个位域,其中每个位表示某些特定事物,那么您可以保留预计算机掩码,它仅在特定位位置有一个将使用该面具进行测试。例如,要检查一个字节,预计算机掩码将是:
#define BIT_0 0x01 //(00000001)
#define BIT_1 0x02 //(00000010)
#define BIT_2 0x04 //(00000100)
#define BIT_3 0x08 //(00001000)
#define BIT_4 0x10 //(00010000)
#define BIT_5 0x20 //(00100000)
#define BIT_6 0x40 //(01000000)
#define BIT_7 0x80 //(10000000)
所以要测试第 4 位,byte
我们必须做return (byte & BIT_4)
或return (byte & BIT_4) != 0;
根据位位置代表的宏名称可以设置。