Last active
May 6, 2017 17:13
-
-
Save samueltcsantos/8a6e3b66d3f09385a19a8814c9aa1b13 to your computer and use it in GitHub Desktop.
Convert from decimal to hexadecimal
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> | |
#define BITS 64 | |
/** | |
* @desc Algorithm to convert decimal to hexadecimal. | |
* | |
* Compile: gcc decimal-hexa.c -o toHex | |
* Run: ./toHex 250 | |
* | |
* @author Samuel T. C. Santos | |
*/ | |
void strrev(char str[]){ | |
int len = strlen(str); | |
char tmp, i, j; | |
int middle = len /2; | |
for(i=0, j=len-1; i < j; i++,j--){ | |
tmp = str[i]; | |
str[i] = str[j]; | |
str[j] = tmp; | |
} | |
} | |
int main(int argc, char **argv){ | |
char HEX_VALUES[] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; | |
int number = (int) atoi(argv[1]); | |
printf("Decimal: %d \n", number); | |
//Need 65 because the last is '\0' | |
char hexadecimal[BITS + 1]; | |
//r - remainder , q - quotient | |
int q=number ,r=0, index=0; | |
while (q != 0){ | |
r = number % 16; | |
q = number / 16; | |
hexadecimal[index] = HEX_VALUES[r]; | |
number = q; | |
index++; | |
} | |
hexadecimal[index] = '\0'; | |
strrev(hexadecimal); | |
printf("Hexadecimal: %s \n", hexadecimal); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment