我正在阅读 这篇文章用 Xor 交换单个位以交换给定数字的位。
作为*交换位范围的示例,假设我们有 b = 00101111(以二进制表示)并且我们希望将 n = 3 个连续位从 i = 1(右起第二位)开始与 3 个连续位交换从 j = 5 开始;结果将是 r = 11100011(二进制)。*但我无法理解它是如何工作的。
给定的代码是
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));
请任何人告诉我这段代码是如何工作的。