cbit-manipulationbitwise-operators

Decimal to binary using Bitwise operator


#include <stdio.h>

int main()
{
  int decimal_num, c, result;

  printf("Enter an integer in decimal number system\n");
  scanf("%d", &decimal_num);

  for (c = 31; c >= 0; c--)
  {
    result = decimal_num >> c;

    if (result & 1)
      printf("1");
    else
      printf("0");
  }

  printf("\n");

  return 0;
}

This code takes a decimal number and converts it into binary using bitwise operator. I am having a hard time understanding the logic inside the for loop result = decimal_num >> c and why does it iterate from for (c = 31; c >= 0; c--). I understand the basics of bitwise AND, OR, XOR and NOT and I know that when an odd number is ANDED with '1' the result is '1' else '0'(because the least significant bit of all odds are 1).


Solution

  • Here's an explanation of the code :

    The program scans the bitwise representation of the decimal number from left to write, working on each bit. The decimal number is supposed to have 32 bits, hence the for loop runs 32 times.

    The first time, the value of c is 31.

    Assuming the bit representation of decimal_num initially is x................................ ( . represents any digit )

    decimal_num >> 31 shifts all bits rightwards 31 times, such that the first bit is shifted at the right most end. The result is 0000000000000000000000000000x. Note that when digits are shifted, 0 is pre-pended to the left end.

    The result is then checked to see if it was 0 or 1, and printed accordingly. 0000000000000000000000000000x & 00000000000000000000000000001 = 1 if x is one 0000000000000000000000000000x & 00000000000000000000000000001 = 0 if x is zero.

    Moving on, and checking the second bit when c is 30. :

    .Y..............................

    decimal_num >> 30 results in 000000000000000000000000000000.Y

    000000000000000000000000000.Y & 00000000000000000000000000001 = 1 if Y is one 000000000000000000000000000.Y & 00000000000000000000000000001 = 0 if Y is zero.

    We go on printing the results until the last digit.

    Hope this helps you understand.