Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- int main(void){
- int decimal;
- int binary;
- int greater_power;
- // decimal = 24;
- greater_power = 1;
- binary = 0;
- printf("Enter decimal number: ");
- scanf("%d",&decimal);
- //Caluclate the greatest power of 2.
- while (greater_power < decimal){
- greater_power *= 2; // It will keep doubling until it will be greater or equal than the decimal.
- // printf("%d\n", greater_power); // To test how the loop code works :>
- }
- //Example:Great Power = 16|Decimal = 24
- while (greater_power > 0){ //Loops until Greater Power reach 0.
- binary *= 10; //Shift bits to left. IF TRUE: adds 1 |IF FALSE: still multiplied, but 1 will not be added (0).
- if (greater_power <= decimal){ // IF TRUE: 16 <= 24.
- binary += 1; //The Binary 0, will be added by 1. Binary = binary + 1.
- decimal -= greater_power; //Decimal (24) - Greater Power (16) = Decimal will become (8).
- } //Repeat process until Decimal is 0 or = Great Power.
- greater_power /= 2; // IF FALSE: Great Power divided by 2. Until Great Power is <=.
- }
- printf("%d",binary);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement