位操作(清除n位)

use*_*694 0 c c++ bit-manipulation

通过Gayle Laakmann McDowell的书"Cracking the coding interview",在位操作章节中,它发布了一个问题:

找到值(假设数字由4位表示):

1011 & (~0 << 2)
Run Code Online (Sandbox Code Playgroud)

现在,~0 = 1并向左移动两次产生100(= 0100以完成4位).安定1011与0100等于0000.

但是,我的答案是1000.

小智 8

~0 is not 1 but 1111 (or 0xf). The ~ operator is a bitwise NOT operator, and not a logical one (which would be !).

因此,当向左移动2位时,最后4位是1100.并且1100 & 1011是exaclty 1000.