Wednesday, April 24, 2013

Reverse bits in an Integer


A simple function to reverse the bits in an integer

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include "stdio.h"
#include "stdlib.h"

/* Function to reverse the bits
 * Assuming 32 bits.
 * Simple functionality, get the last bit by right shift
 * and insert into the output by ORing and then left shifting.
 * There are better ways to do this.
 */
void reverse(unsigned *input)
{
        unsigned i=0, mask=0x1, res=0x0, tmp = 0x0;
        unsigned in = *input;

        for(i=0; i<32; i++){
                tmp = in & mask;
                in = in >> 1;

                res = res << 1;
                res |= tmp;
        }
        *input = res;
        return;

}

int main(int argc, char **argv)
{

        unsigned input = 0xffffbbbb;
        printf("%x\n", input);
        reverse(&input);
        printf("%x\n", input);

        return 0;
}

[root@Imperfecto_1 ~] gcc run.c && ./a.out
ffffbbbb
ddddffff

[root@Imperfecto_1 ~] echo "ibase=16;obase=2; FFFFBBBB" | bc
11111111111111111011101110111011

[root@Imperfecto_1 ~] echo "ibase=16;obase=2; DDDDFFFF" | bc
11011101110111011111111111111111

No comments:

Post a Comment