Write a program to reverse the bits of a given number.
#include<stdio.h> void Print_Num_inBinary(int); void Reverse_Bits(int*); int main() { int num,bit,status; printf("Enter a Number = "); scanf("%d",&num); Print_Num_inBinary(num); Reverse_Bits(&num); printf("Bits are reversed now"); Print_Num_inBinary(num); return 0; } void Print_Num_inBinary(int n) { int i; printf("\n%d Bit Binary Representation of a Number\n",sizeof(int)*8); for(i = ((sizeof(int)*8)-1);i >= 0;i--) { printf("%d",n >> i & 1); if(!(i%8)) printf(" "); } printf("\n"); } void Reverse_Bits(int *n) { int i,j; for(i = (sizeof(int)*8-1),j=0;j<i;i--,j++) { if(((*n) >> i & 1) != ((*n) >> j & 1)) { *n = *n ^ 1 << i; *n = *n ^ 1 << j; } } }
Output
Enter a Number = 65535
32 Bit Binary Representation of a Number
00000000 00000000 11111111 11111111
Bits are reversed now
32 Bit Binary Representation of a Number
11111111 11111111 00000000 00000000
Enter a Number = 15
32 Bit Binary Representation of a Number
00000000 00000000 00000000 00001111
Bits are reversed now
32 Bit Binary Representation of a Number
11110000 00000000 00000000 00000000