How to reverse the bits in an interger?

Here are some ways to reverse the bits in an integer.

Method1

unsigned int num;            // Reverse the bits in this number.
unsigned int temp = num;     // temp will have the reversed bits of num.

int i;

for (i = (sizeof(num)*8-1); i; i–)
{
temp = temp | (num & 1);
temp <<= 1;
num  >>= 1;
}

temp = temp | (num & 1);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s