2

Possible Duplicate:
C reverse bits in unsigned integer
How does this code work to reverse bits in number?

Given a number n with k bits, (n < 2^k), is there a fast way to do it using bitwise? This is my slow solution:

int reverse_bit(int n, int bit_size) {
    bit_size--;

    int result = 0;
    while (n) {
        if ((n & 1) == 1)
            result += 1 * (1 << bit_size);

        n >>= 1;
        bit_size--;
    }

    return result;
}
Community
  • 1
  • 1
roxrook
  • 13,511
  • 40
  • 107
  • 156
  • 4
    This should have the solution: http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel – nhahtdh Jun 30 '12 at 05:28
  • 3
    Asked before: [1](http://stackoverflow.com/questions/9144800/c-reverse-bits-in-unsigned-integer), [2](http://stackoverflow.com/questions/2515715/bit-reversal-using-bitwise), [3](http://stackoverflow.com/questions/10184089/how-does-this-code-work-to-reverse-bits-in-number). – Alexey Frunze Jun 30 '12 at 06:09
  • Above mentioned duplicates describe it by using C. Here some code which written in more C++ way. `template T reverse(T n, size_t nBits = sizeof(T) * 8) { T reverse = 0; auto mask = 1; for (auto i = 0; i < nBits; ++i) { if (n & mask) { reverse |= (1 << (nBits - i - 1)); } mask <<= 1; } return reverse; }` – Amith Chinthaka Jan 31 '17 at 11:48

0 Answers0