OiO.lk Blog C# Decimal to binary using Bitwise operator
C#

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).



You need to sign in to view this answers

Exit mobile version