Created
December 22, 2018 18:29
-
-
Save shannietron/04d6b655772301103f0a1012ba48b17a to your computer and use it in GitHub Desktop.
Implementation of the double dabble algorithm to convert binary to BCD.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
char *binary(unsigned int dec); | |
int main(int argc, char * argv [] ){ | |
unsigned int input = strtol(argv[1],NULL,10); | |
unsigned int temp = 0x0; | |
printf("%s",binary(temp)); | |
printf(" %s = %u \n",binary(input),input); | |
for(int i = 0; i<12;i++){ | |
temp=temp <<1; | |
input & 0x800 ? temp = temp^0x1: '0'; | |
input=input <<1; | |
printf("%s",binary(temp)); | |
printf(" %s ",binary(input)); | |
if(((temp & 0xF) >= 0x4)){ // checks if the ones place > 4 | |
printf("ONES – Adding 0x3"); | |
temp = temp+0x3; | |
} | |
if(((temp & 0xF0) >= 0x40)){ // checks if the tens place > 4 | |
printf("TENS – Adding 0x3"); | |
temp = temp+0x30; | |
} | |
if(((temp & 0xF00) >= 0x400)){ // checks if the hundreds place > 4 | |
printf("TENS – Adding 0x3"); | |
temp = temp+0x300; | |
} | |
printf("\n"); | |
} | |
} | |
char *binary(unsigned int dec){ | |
static char bin[13]; | |
for(int i = 0; i<12;i++){ | |
bin[i] = dec & 0x800 ? '1' : '0'; | |
dec = dec << 1; | |
} | |
bin[12]='\0'; | |
return (bin); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment