Monday, February 17, 2020

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 (= 31; c >= 0; c--)
  {
    k = n >> c;
    if (& 1)
      printf("1");
    else
      printf("0");
  }
  printf("\n");
  return 0;
}
Output of the program:
Decimal to binary C program output
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

#include <stdio.h>
#include <stdlib.h>
char *decimal_to_binary(int);
main()
{
   int n, c, k;
   char *pointer;
 
   printf("Enter an integer in decimal number system\n");
   scanf("%d",&n);
 
   pointer = decimal_to_binary(n);
   printf("Binary string of %d is: %s\n", n, t);
 
   free(pointer);
 
   return 0;
}
char *decimal_to_binary(int n)
{
   int c, d, count;
   char *pointer;
 
   count = 0;
   pointer = (char*)malloc(32+1);
 
   if (pointer == NULL)
      exit(EXIT_FAILURE);
   
   for (= 31 ; c >= 0 ; c--)
   {
      d = n >> c;
   
      if (& 1)
         *(pointer+count) = 1 + '0';
      else
         *(pointer+count) = 0 + '0';
   
      count++;
   }
   *(pointer+count) = '\0';
 
   return  pointer;
}
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.

No comments:

Post a Comment