有效地创建一个具有1全1但一个为0的int保持为0的int

asi*_*mes 5 c bitwise-operators

我有一个任务,要求只使用这些运算符执行许多功能:

!〜&^ | + << >>

在一些问题中,如果它包含任何1,则使一些整数x变为全1,但如果它为0则保持为0是有用的.我这样做的原因是我可以像这样返回y或z:

// One of the two conditional values is now 0
int conditionalA = mask&y;
int conditionalB = ~mask&z;

// One of the values is combined with 0 using |
int out = conditionalA|conditionalB;

return out;
Run Code Online (Sandbox Code Playgroud)

在哪里我做了这样的面具:

// Make any x other than 0 all 1s
int mask = x;
mask |= mask>>1;
mask |= mask>>2;
mask |= mask>>4;
mask |= mask>>8;
mask |= mask>>16;

mask |= mask<<1;
mask |= mask<<2;
mask |= mask<<4;
mask |= mask<<8;
mask |= mask<<16;
Run Code Online (Sandbox Code Playgroud)

必须有一个更好的方法来使掩码全1或0,但我想不出更有效的解决方案.同样,如果x为0,则0保持为0非常重要.

编辑:如果语句不是一个选项

eca*_*mur 6

假设2的补码:

int mask = !x + ~0;
Run Code Online (Sandbox Code Playgroud)

!地图的任何非零值,001,那么我们添加~0(-1)来获得-10分别.