You are here

Decimal to binary in C

Decimal to binary conversion
Decimal to binary in C to convert an integer from decimal number system (base-10) to binary number system (base-2). 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).

C program to convert decimal to binary

#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;
}

Output of the program:
Decimal to binary C program output

Download Decimal binary program.

This code only prints binary of an integer. Still, we may wish to perform operations on binary, so in the program below, we store the binary in a string. We create a function that returns a pointer to it (the binary of the number passed).

Decimal to binary conversion in C

#include <stdio.h>
#include <stdlib.h>

char *decimal_to_binary(int);

int main()
{
  int n;
  char *p;

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

  p = decimal_to_binary(n);
  printf("Binary string of %d is: %s\n", n, p);

  free(p);

  return 0;
}

char *decimal_to_binary(int n)
{
  int c, d, t;
  char *p;

  t = 0;
  p = (char*)malloc(32+1);

  if (p == NULL)
    exit(EXIT_FAILURE);

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

    if (d & 1)
      *(p+t) = 1 + '0';
    else
      *(p+t) = 0 + '0';

    t++;
  }
  *(p+t) = '\0';

  return  p;
}

We allocate memory dynamically because we can't return a pointer to a local variable (character array in this case). If we return it to a local variable, then the program may crash, or we get an incorrect result.