Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C reverse binary [duplicate]

Possible Duplicate:
C reverse bits in unsigned integer

How can I reverse a binary number only using binary operators?

E.g:

11100000 -> 00000111
00110100 -> 00101100
00111111 -> 11111100
like image 932
Frederico Schardong Avatar asked Dec 05 '22 14:12

Frederico Schardong


2 Answers

For this sort of thing I recommend that you take a look at the awesome page Bit Twiddling Hacks.

Here is just one example solution taken from that page:

Reverse the bits in a byte with 3 operations (64-bit multiply and modulus division)

unsigned char b; // reverse this (8-bit) byte 
b = (b * 0x0202020202ULL & 0x010884422010ULL) % 1023;

And as pointed out in the comments, here's another option:

Reverse an N-bit quantity in parallel in 5 * lg(N) operations

unsigned int v; // 32-bit word to reverse bit order

// swap odd and even bits
v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1);
// swap consecutive pairs
v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2);
// swap nibbles ... 
v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4);
// swap bytes
v = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8);
// swap 2-byte long pairs
v = ( v >> 16             ) | ( v               << 16);
like image 166
Mark Byers Avatar answered Dec 28 '22 08:12

Mark Byers


Take a look at Bit Twiddling Hacks. There's an entire section on reversing bit sequences.

like image 31
Joey Avatar answered Dec 28 '22 08:12

Joey