You are here

Decimal to binary in C

Decimal to binary in C programming: C program to convert an integer from decimal number system (base-10) to binary number system (base-2). Size of an integer is assumed to be 32 bits. We will 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 1 otherwise it is 0 (zero).

C program to convert decimal to binary

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.   int n, c, k;
  6.  
  7.   printf("Enter an integer in decimal number system\n");
  8.   scanf("%d", &n);
  9.  
  10.   printf("%d in binary number system is:\n", n);
  11.  
  12.   for (c = 31; c >= 0; c--)
  13.   {
  14.     k = n >> c;
  15.  
  16.     if (k & 1)
  17.       printf("1");
  18.     else
  19.       printf("0");
  20.   }
  21.  
  22.   printf("\n");
  23.  
  24.   return 0;
  25. }

Output of the program:
Decimal to binary C program output

Download Decimal binary program.

This code only prints binary of an integer, but we may wish to perform operations on binary, so in the program below we are storing the binary in a string. We create a function which returns a pointer to string which is the binary of the number passed as an argument to the function.

C code to store decimal to binary conversion in a string

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. char *decimal_to_binary(int);
  5.  
  6. main()
  7. {
  8.    int n, c, k;
  9.    char *pointer;
  10.    
  11.    printf("Enter an integer in decimal number system\n");
  12.    scanf("%d",&n);
  13.    
  14.    pointer = decimal_to_binary(n);
  15.    printf("Binary string of %d is: %s\n", n, t);
  16.    
  17.    free(pointer);
  18.    
  19.    return 0;
  20. }
  21.  
  22. char *decimal_to_binary(int n)
  23. {
  24.    int c, d, count;
  25.    char *pointer;
  26.    
  27.    count = 0;
  28.    pointer = (char*)malloc(32+1);
  29.    
  30.    if (pointer == NULL)
  31.       exit(EXIT_FAILURE);
  32.      
  33.    for (c = 31 ; c >= 0 ; c--)
  34.    {
  35.       d = n >> c;
  36.      
  37.       if (d & 1)
  38.          *(pointer+count) = 1 + '0';
  39.       else
  40.          *(pointer+count) = 0 + '0';
  41.      
  42.       count++;
  43.    }
  44.    *(pointer+count) = '\0';
  45.    
  46.    return  pointer;
  47. }

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