Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse an int but grouped by 2 bit in C?

Like this:

input:  10010011
(10->01->00->11)

output: 11000110
(11->00->01->10)


input:  11010001
(11->01->00->01)

output: 01000111
(01->00->01->11)

Anyone has any ideas about that?

like image 244
Hanfei Sun Avatar asked Dec 12 '22 23:12

Hanfei Sun


1 Answers

Fewer operations than lserni's algorithm:

uint32_t reverseByTwo(uint32_t value) {
    value = ((value & 0x03030303) << 2) | ((value >> 2) & 0x03030303); // swap adjacent pairs
    value = ((value & 0x0F0F0F0F) << 4) | ((value >> 4) & 0x0F0F0F0F); // swap nibbles
    value = ((value & 0x00FF00FF) << 8) | ((value >> 8) & 0x00FF00FF); // swap bytes
    value = ((value & 0x0000FFFF) << 16) | ((value >> 16) & 0x0000FFFF);
    return value;
}

For 64-bit values just add another swap for the 32-bit halves, for smaller types, just leave out the last few swaps.

like image 165
Daniel Fischer Avatar answered Dec 26 '22 21:12

Daniel Fischer