Reverse of a number

This program is to reverse a number

Logic:

Loop through all the bits of an integer.
If a bit at ith position is set in the i/p no.
then set the bit at (NO_OF_BITS – 1) – i in o/p.
Where NO_OF_BITS is number of bits present in the given number.

#include <stdio.h>
#define MAX_BIT (sizeof(int) * 8)

int display_binary(unsigned int num)
{
   int i;
   for(i = MAX_BIT-1; i>=0; i--)
   {
       if((num >> i)&1)
         printf("1");
       else
         printf("0");
   }
}

int reverse_num( unsigned int num, int *revnum)
{
    int i = 0;
    for(i; i <MAX_BIT; i ++)
    {
        if ((num >> i) & 1)
          *revnum = *revnum | 1UL << (MAX_BIT - i -1);
    }
    
    
}

int main()
{
  unsigned int num, revnum;
  printf("\n Enter the first number : ");
  scanf("%u",&num);
  printf("\n The original number is: %u decimal:", num);
  display_binary (num);
  printf("\n\n");
  
  reverse_num(num, &revnum);
  printf("\n The reverse of a number is %u decimal:", revnum);
  display_binary(revnum);
  
  return 0;
}

Output:

 Enter the first number : 255

 The original number is: 255 decimal:00000000000000000000000011111111

 The reverse of a number is 4278190080 decimal:11111111000000000000000000000000


Categories: C Language

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 )

Connecting to %s

%d bloggers like this: