Bit reversal of an integer, ignoring integer size and endianness

Posted by ??O????? on Stack Overflow See other posts from Stack Overflow or by ??O?????
Published on 2008-09-15T15:10:49Z Indexed on 2010/03/22 2:11 UTC
Read the original article Hit count: 591

Filed under:
|
|

Given an integer typedef:

typedef unsigned int TYPE;

or

typedef unsigned long TYPE;

I have the following code to reverse the bits of an integer:

TYPE max_bit= (TYPE)-1;

void reverse_int_setup()
{
    TYPE bits= (TYPE)max_bit;

    while (bits <<= 1)
        max_bit= bits;
}

TYPE reverse_int(TYPE arg)
{
    TYPE    bit_setter= 1, bit_tester= max_bit, result= 0;

    for (result= 0; bit_tester; bit_tester>>= 1, bit_setter<<= 1)
        if (arg & bit_tester)
            result|= bit_setter;
    return result;
}

One just needs first to run reverse_int_setup(), which stores an integer with the highest bit turned on, then any call to reverse_int(arg) returns arg with its bits reversed (to be used as a key to a binary tree, taken from an increasing counter, but that's more or less irrelevant).

Is there a platform-agnostic way to have in compile-time the correct value for max_int after the call to reverse_int_setup(); Otherwise, is there an algorithm you consider better/leaner than the one I have for reverse_int()?

Thanks.

© Stack Overflow or respective owner

Related posts about c

    Related posts about bit-manipulation