右移按位与
Right shift with bitwise AND
来自 top answer 的解决方案是
To check a bit, shift the number x to the right, then bitwise AND it:
bit = (number >> x) & 1;
That will put the value of bit x into the variable bit.
让我感到困惑的是,假设如下:
unsigned number = 5; //0101
int x = 2; //
轮班 (number >> x)
后,我们得到 0001
。但是我们移开了第 1 位和第 2 位,所以当我们执行 按位 AND 时,我们不是针对 third 位而不是秒,其中x = 2
?这是否意味着如果我想检查位 x
是否已设置,我不应该这样做:
bit = (number >> (x - 1)) & 1);
位数表示2的幂。因此,当 x
为二时,您在谈论位 2 = 2**2 = 4.
最低有效位(或者 'right most' 位,如果你喜欢位 0,而不是位 1。
此外,除非您的 'bit number' 在变量中,否则没有理由实际进行位移。
例如,要测试值的第 5 位,只需执行
if (variable & 0x20)
bit_is_set();
这里 0x20
就是 2**5, (or 1 << 5)
是的,您正在对第三位进行按位与运算。考虑 x
是零索引的,即第一位是位 0。
你说:
After a shift (number >> x)
we get 0001
. But we shifted off bits 1 and 2 and so when we do the bitwise AND, aren't we doing it against the third bit and not the second, where x = 2
? Doesn't this mean that if I want to check if bit x
is set, shouldn't I do:
bit = (number >> (x - 1)) & 1);
要获得第一个最低有效位的值,您需要(number >> 0) & 1
。
要获得第二个最低有效位的值,您需要 (number >> 1) & 1
.
要获得第 3 个最低有效位的值,您需要 (number >> 2) & 1
。
等等
换句话说,
第 1 个表示要移动 0 位
2nd 表示要移位 1 位
3rd 表示要移位 2 位
Nth 表示要移位 N-1 位
我希望这能让你更清楚一点。
来自 top answer 的解决方案是
To check a bit, shift the number x to the right, then bitwise AND it:
bit = (number >> x) & 1;
That will put the value of bit x into the variable bit.
让我感到困惑的是,假设如下:
unsigned number = 5; //0101
int x = 2; //
轮班 (number >> x)
后,我们得到 0001
。但是我们移开了第 1 位和第 2 位,所以当我们执行 按位 AND 时,我们不是针对 third 位而不是秒,其中x = 2
?这是否意味着如果我想检查位 x
是否已设置,我不应该这样做:
bit = (number >> (x - 1)) & 1);
位数表示2的幂。因此,当 x
为二时,您在谈论位 2 = 2**2 = 4.
最低有效位(或者 'right most' 位,如果你喜欢位 0,而不是位 1。
此外,除非您的 'bit number' 在变量中,否则没有理由实际进行位移。
例如,要测试值的第 5 位,只需执行
if (variable & 0x20)
bit_is_set();
这里 0x20
就是 2**5, (or 1 << 5)
是的,您正在对第三位进行按位与运算。考虑 x
是零索引的,即第一位是位 0。
你说:
After a shift
(number >> x)
we get0001
. But we shifted off bits 1 and 2 and so when we do the bitwise AND, aren't we doing it against the third bit and not the second, wherex = 2
? Doesn't this mean that if I want to check if bitx
is set, shouldn't I do:bit = (number >> (x - 1)) & 1);
要获得第一个最低有效位的值,您需要(number >> 0) & 1
。
要获得第二个最低有效位的值,您需要 (number >> 1) & 1
.
要获得第 3 个最低有效位的值,您需要 (number >> 2) & 1
。
等等
换句话说,
第 1 个表示要移动 0 位
2nd 表示要移位 1 位
3rd 表示要移位 2 位
Nth 表示要移位 N-1 位
我希望这能让你更清楚一点。