简体   繁体   中英

Swapping individual bits with XOR

I was reading this article swapping of individual bits with Xor to swap the bits of a given number.

As an example of * swapping ranges of bits suppose we have have b = 00101111 (expressed in binary) and we want to swap the n = 3 consecutive bits starting at i = 1 (the second bit from the right) with the 3 consecutive bits starting at j = 5; the result would be r = 11100011 (binary). *but i could not able to understand how it is working.
Given code is

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));

Please any one clear me how this code is working.

Lets do this in steps: (b >> i) and (b >> j) move the bits you want to swap to be the first bits.

((b >> i) ^ (b >> j)) then XORs them.

((1U << n) - 1) this expression is simply the number 1111...1 n times (in binary)

So in total x is the result of the XOR, with all the other bits being 0.

(x << i) and (x << j) move the bits back to their right place.

with ((x << i) | (x << j)) all bits that are set in either one is set in the result.

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.

Well, it is using shifting to limit the bits which are effected by each operation (ie. shuffling the others out of the picture to get work done, and only operate with those we care about). As part of that, it flips those bits with xor, shifts them back, and flips them back into the original by x-oring with the original. ...and because that is as clear as mud...

eg.

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!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM