给定一个整数,交换第 i 位和第 j 位。
我已经尝试自己解决这个问题。各位是不是觉得太“罗嗦”(太长)了?
int swap_bit(int num, int i, int j){
int a=(num>>i) & 1; //i-th bit
int b=(num>>j) & 1; //j-th bit
int mask1=~(1<<i); // create mask to clear i-th bit
int mask2=~(1<<j); // create mask to clear j-th bit
num=num & mask1 & mask2;
num=num | (a<<j);
num=num | (b<<i);
return num;
}
最佳答案
我总是引用 https://graphics.stanford.edu/~seander/bithacks.html对于任何与比特相关的东西。
用 XOR 交换单个位
unsigned int i, j; // positions of bit sequences to swap
unsigned int n; // number of consecutive bits in each sequence
unsigned int b; // bits to swap reside in b
unsigned int r; // bit-swapped result goes here
unsigned int x = ((b >> i) ^ (b >> j)) & ((1U << n) - 1); // XOR temporary
r = b ^ ((x << i) | (x << j));
作为交换位范围的示例,假设我们有 b = 00101111(以二进制表示)并且我们想要交换从 i = 1(右数第二位)开始的 n = 3 个连续位与 3从 j = 5 开始的连续位;结果将是 r = 11100011(二进制)。
这种交换方法类似于通用 XOR 交换技巧,但用于对单个位进行操作。变量 x 存储我们要交换的位值对的异或结果,然后这些位被设置为它们自己与 x 异或的结果。当然,如果序列重叠,结果是不确定的。
对于 n = 1 的特殊情况,代码简化为:
unsigned int i, j; // positions of bit sequences to swap
unsigned int b; // bits to swap reside in b
unsigned int r; // bit-swapped result goes here
unsigned int x = ((b >> i) ^ (b >> j)) & 1U; // XOR temporary
r = b ^ ((x << i) | (x << j));
关于c++ - 交换整数的第 i 位和第 j 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40567756/