Ex: Like binary value 1010 then after swap pair bit position value 0101
I need to swap pair of bit positions like the pair to swap 1st and 2nd bit position values similarly bit positions 34, 56, 78, ...
Muthuraman
2010-08-03 13:22:55
+1
A:
unsigned char swapped = ((original & 85) << 1) | ((original & 170) >> 1);
walkytalky
2010-08-03 13:20:31
+7
A:
int pairwise_bit_swap(int a) {
return ((a & 0x55555555L) << 1) | ((a & 0xAAAAAAAAL) >> 1);
}
tdammers
2010-08-03 13:22:32
+1. Very simple code using a reasonably clear technique. As a portability note, it is possible that some compilers may use an int with a sufficiently large range that this code will cause the int to be truncated.
Brian
2010-08-03 13:38:22
Remo.D
2010-08-03 15:31:11
Also note that this will only work on a 32 bits int. The fact that you put L at the end is of no help if int is 64 bits!
Remo.D
2010-08-03 15:32:09
A:
If u want swap odd position bits to even position(Like swap pair bits 1 2 , 3 4 , 5 6 and 7 8 )
unsigned char a,x,y,z;
a = 2+4+8+128;
x = a & 170;
y = a & 85;
z = (x>>1)|(y<<1);
Z is the answer.
Similarly we can swap 16 bit and so on. Please, work out the above sample scenario...
Muthuraman
2010-08-03 13:34:56
A:
((x << 1) & 0xAAAAAAAA) |( (x >>1) & 0x55555555)
where x in the number.
Praveen S
2010-08-03 13:40:13