我正在开发一个编程项目,其中一个任务是编写一个函数,返回标记最低有效位的掩码。你有什么想法可以使用位运算符确定该值吗?
ex:
0000 0000 0000 0000 0000 0000 0110 0000 = 96
What can I do with the # 96 to turn it into:
0000 0000 0000 0000 0000 0000 0010 0000 = 32
我已经努力思考了数小时,但却无法弄清楚这个问题。非常感谢您的任何帮助!
我正在开发一个编程项目,其中一个任务是编写一个函数,返回标记最低有效位的掩码。你有什么想法可以使用位运算符确定该值吗?
ex:
0000 0000 0000 0000 0000 0000 0110 0000 = 96
What can I do with the # 96 to turn it into:
0000 0000 0000 0000 0000 0000 0010 0000 = 32
我已经努力思考了数小时,但却无法弄清楚这个问题。非常感谢您的任何帮助!
x &= -x; /* clears all but the lowest bit of x */
x &= ~x + 1
起作用。 - Tavian Barnesx & 1
x & -x
log2(x & -x)
以下是JavaScript中的示例:
let x = 0b1101000;
console.log(x & 1); // 0 (the farthest-right bit)
console.log(x & -x); // 8 (the farthest-right 1 by itself)
console.log(Math.log2(x & -x); // 3 (the zero-based index of the farthest-right 1)
int leastSignificantBit(int number)
{
int index = 0;
while ((~number) & 1) {
number >>= 1;
index++;
}
return 1 << index;
}
1 << index
)。 - cHao