4

我正在阅读 这篇文章用 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));

请任何人告诉我这段代码是如何工作的。

4

2 回答 2

4

让我们分步执行此操作: (b >> i) 和 (b >> j) 将要交换的位移动为第一位。

((b >> i) ^ (b >> j)) 然后对它们进行异或。

((1U << n) - 1) 这个表达式只是数字 1111...1 n 次(二进制)

所以总共 x 是 XOR 的结果,所有其他位都是 0。

(x << i) 和 (x << j) 将位移回正确的位置。

使用 ((x << i) | (x << j)) 在任一设置中设置的所有位都在结果中设置。

And b ^ ((x << i) | (x << j)) means we XOR the original with the XOR'd bits of both parts. Note that x ^ x ^ y = y so since in both parts the original appears twice in the xor, but the second part only once, we get bit swapping.

于 2012-09-11T06:38:15.553 回答
3

好吧,它使用移位来限制每个操作所影响的位(即,将其他位从图片中移出以完成工作,并且只对我们关心的那些位进行操作)。作为其中的一部分,它使用 xor 翻转这些位,将它们移回,并通过与原始 x-oring 将它们翻转回原始。...因为那像泥一样清澈...

例如。

XX...XX001 ^ XX..XX111 = XX..XX110  (xor the 2 sequences together + trash bits)
XX..XX110 & 0...0111 = 110 (keep only those bits we care about)
00101111 ^ 11001100 = 11100011 (and magic!)
于 2012-09-11T06:33:02.253 回答