Convert Decimal to Binary in C

Convert Decimal to Binary

The size of an integer is assumed to be 32 bits. We use the bitwise operator “AND” to perform the desired task. We right shift the original number by 31, 30, 29, …, 1, 0 bits using a for loop and bitwise AND the number obtained with 1(one) if the result is 1, then that bit is one otherwise zero (0).

#include <stdio.h>
int main()
{
  int n, c, k;

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

  printf("%d in binary number system is:\n", n);

  for (c = 31; c >= 0; c--)
  {
    k = n >> c;

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

  printf("\n");

  return 0;
}

   Reprint policy


《Convert Decimal to Binary in C》 by Isaac Zhou is licensed under a Creative Commons Attribution 4.0 International License
  TOC