Advertisement
nahidiac

Decimal to Binary Conversion using String

Dec 11th, 2019
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.43 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.     int decimal;
  6.     char binary[100];
  7.  
  8.     printf("Enter a decimal number: ");
  9.     scanf("%d", &decimal);
  10.  
  11.     int n = 1;
  12.  
  13.     while(pow(2, n) <= decimal)
  14.     {
  15.         n++;
  16.     }
  17.  
  18.     int i;
  19.  
  20.     for(i = n-1; i >= 0; i--)
  21.     {
  22.         binary[i] = (decimal % 2) + '0';
  23.  
  24.         decimal = decimal/2;
  25.     }
  26.  
  27.     binary[n] = '\0';
  28.  
  29.     printf("%s\n", binary);
  30.  
  31.     return 0;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement