Reputation: 11
Hi all I am writing a C program that asks the user for an unsigned integer. The program will then call a function unsigned int reverse_bits(unsigned int n) This function should return an unsigned integer whose bits are the same as those of n but in reverse order. Print to screen the integer whose bits are in reverse order.
Example:
User enters:
12 (binary 16 bits is 0000000000001100)
Program print to screen:
12288 (0011000000000000)
This is the code i have but it does not output the right answer:
#include <stdio.h>
//function prototype
unsigned int reverse_bits(unsigned int n);
int main(void) {
unsigned int n;
unsigned int bits;
printf("Enter an unsigned integer: ");
scanf("%u",&n);
bits = reverse_bits(n);
printf("%u\n",bits);
return 0;
}
unsigned int reverse_bits(unsigned int n) {
unsigned int reverse = 0;
while (n > 0) {
reverse = reverse << 1;
if((n & 1) == 1) {
reverse = reverse | 1;
}
n = n >> 1;
}
return reverse;
}
This does not give me 12288 when I enter 12, it gives me 3, what did I do wrong?
Upvotes: 0
Views: 342
Reputation: 152
The result depends on how many bits an unsigned int
is stored on your machine. It is usually 4 bytes (32 bits). So, in your case 12
(00000000000000000000000000001100
in binary) becames 805306368
(00110000000000000000000000000000
in binary).
Apart from that, you need to iterate over all bits of an unsigned int
:
for (size_t i = 0; i < sizeof(unsigned int) * 8; i++) {
reverse = reverse << 1;
if((n & 1) == 1) {
reverse = reverse | 1;
}
n = n >> 1;
}
Upvotes: 3