📜  get ith bit (1)

📅  最后修改于: 2023-12-03 15:30:53.714000             🧑  作者: Mango

获取第i位的位值

当我们需要对二进制数的某一位进行操作时,我们需要先获取该位的位值。这时我们需要一个函数来帮助我们获取第i位的位值。

方案

我们可以先让数字x向右移动i位(即 x >> i),使我们需要获取的位移到二进制数的最末位,然后通过 & 运算符,将数字x的最末位与数字1相与(即 x & 1),得到我们需要的位的位值。

代码实现
int getIthBit(int x, int i) {
    return (x >> i) & 1;
}
def get_ith_bit(x: int, i: int) -> int:
    return (x >> i) & 1
测试

以下是一个用于测试的代码:

#include <iostream>

int main() {
    int x = 42;
    std::cout << "The binary representation of " << x << " is " << std::bitset<8>(x) << std::endl;
    for (int i = 0; i < 8; i++) {
        std::cout << "The " << i << "-th bit is " << getIthBit(x, i) << std::endl;
    }
    return 0;
}
x = 42
print(f'The binary representation of {x} is {x:b}')
for i in range(8):
    print(f'The {i}-th bit is {get_ith_bit(x, i)}')

其输出结果为:

The binary representation of 42 is 00101010
The 0-th bit is 0
The 1-th bit is 1
The 2-th bit is 0
The 3-th bit is 1
The 4-th bit is 0
The 5-th bit is 1
The 6-th bit is 0
The 7-th bit is 0