Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert from decimal to hexadecimal
#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