将所有位设置为最低有效位

0 c binary bit-manipulation

如果我有一个xtype int,如何获取xLSB 的值并将数字中的所有其他位设置为该LSB?

我一直在与位运算符和逻辑运算符打交道,这有点(没有双关语),我知道它们是如何工作的。

移位运算符x >> 3x << 3左,右分别×3位的位移位,我知道我们可以使用运营商如^ |&为瞎搞与操纵位。我在理解此特定问题的逻辑时遇到了麻烦。

编辑:我们被允许用于此的运算符是!〜&^ | + << >>

PSk*_*cik 5

从字面上看:

type x /*=some value*/;
_Bool lsb = x&1;
x = lsb ? ~(type)0 : (type)0;
Run Code Online (Sandbox Code Playgroud)

在2的补码体系结构上优化编译器使其无分支,等效于:

 type x /*=some value*/;
_Bool lsb = x&1;
 x = -lsb;
Run Code Online (Sandbox Code Playgroud)

(或-(x&1)没有中介lsb变量。)

https://gcc.godbolt.org/z/2NXFpS