交换整数的i和j位

时间:2016-11-12 21:18:07

标签: c++ bit-manipulation bit

给定一个整数,交换第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;
}

1 个答案:

答案 0 :(得分:3)

我总是将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));