Advertisement
Sierra_ONE

Conversion: Decimal to Binary

Sep 17th, 2023 (edited)
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.11 KB | Source Code | 0 0
  1. #include <stdio.h>
  2.  
  3. int main(void){
  4.     int decimal;
  5.     int binary;
  6.     int greater_power;
  7.    
  8. //  decimal = 24;
  9.     greater_power = 1;
  10.     binary = 0;
  11.    
  12.     printf("Enter decimal number: ");
  13.     scanf("%d",&decimal);
  14.    
  15.     //Caluclate the greatest power of 2.
  16.     while (greater_power < decimal){
  17.        
  18.         greater_power *= 2; // It will keep doubling until it will be greater or equal than the decimal.
  19.        
  20. //      printf("%d\n", greater_power); // To test how the loop code works :>
  21.     }
  22.    
  23.    
  24.     //Example:Great Power = 16|Decimal = 24
  25.     while (greater_power > 0){  //Loops until Greater Power reach 0.
  26.  
  27.         binary *= 10; //Shift bits to left. IF TRUE: adds 1 |IF FALSE: still multiplied, but 1 will not be added (0).
  28.        
  29.         if (greater_power <= decimal){ // IF TRUE: 16 <= 24.
  30.        
  31.             binary += 1; //The Binary 0, will be added by 1. Binary = binary + 1.
  32.            
  33.             decimal -= greater_power; //Decimal (24) - Greater Power (16) = Decimal will become (8).
  34.  
  35.         } //Repeat process until Decimal is 0 or = Great Power.
  36.  
  37.         greater_power /= 2; // IF FALSE: Great Power divided by 2. Until Great Power is <=.
  38.     }
  39.    
  40.     printf("%d",binary);
  41.  
  42.     return 0;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement