c++ - 交换整数的第 i 位和第 j 位

标签 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;
}

最佳答案

我总是引用 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/

相关文章:

c++ - 在同一应用程序/模块中使用 CORBA 接口(interface)的不同不兼容版本?

c++ - 线程代码解释器中的手动操作调用(打破正常流程)

c++ - 为什么在C++宏上扩展为注释时会出现 “Expected a declaration”错误?

java - 移位以获得余数

c - 为什么我们将 (temp>>11) 乘以 2 来找到此代码中的第二个

c - 通过 fopen 在 C 中访问二进制 MP3 header

c++ - std::map - 插入作为嵌套结构的主体

java - 有人可以向我解释以下 Java 代码在做什么吗?

c - 如何读取 unsigned int 的特定位

c++ - 将 64 位整数中的每隔一位与 32 位整数进行比较