Decimal to binary using Bitwise operator

11,418

Here's an explanation of the code :

The program scans the bitwise representation of the decimal digit from left to write, working on each bit. The decimal digit 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.

Share:
11,418

Related videos on Youtube

Ganesh Thampi
Author by

Ganesh Thampi

A budding professional with extensive knowledge of programming and basics of database management systems. Have Good communication and interpersonal skills. A passionate internet researcher with a desire to learn, practice and repeat.

Updated on June 04, 2022

Comments

  • Ganesh Thampi
    Ganesh Thampi over 1 year
    #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).

    • Some programmer dude
      Some programmer dude over 5 years
      Use a debugger to step through the code line by line. And read more about the shift operators.
    • Jean-Baptiste Yunès
      Jean-Baptiste Yunès over 5 years
      0-31: 32 iterations, that should be related to the bit size of ints on that machine. decimal_num>>c + result&1 looks like something to isolate and examine a single bit... Read about shifting