Decimal to hex conversion is needed in different occasions, but most frequently when you need to represent a number for a specific computer program. Here you will learn how to do the calculations and also how to create a converter in C language. Of course, you can use the online converter, as well.
Input the decimal value | The hex number is | |
---|---|---|
The hexadecimal number system uses 16 characters to represent the numbers. These characters(digits) include the decimal digits (0..9) and the first six letters (A..F). It doesn't matter if you use uppercase or lowercase letters. Hex values are often preceded by the 0x (zero x) prefix. It indicates that the value that follows is a hexadecimal number.
To convert from decimal to hex, we use the following algorithm:
Example: 1610 = ? (hex)
Part 1: 16 / 16 = 1 and remainder 0.
Remember the result(1) and the remainder (0).
Repeat Part 1, using the result: 1 / 16
= 0 and remainder 1. We reached result 0, so we continue with 3:
Part 3: The remainders that we have are
0 and 1. No substitution is needed. Their reversed order is 10. This
is the final result:
Just like the other converters that we have done, we will create a program that converts up to 64 bit numbers. For that reason we use unsigned long for the input type.
Note that long is not guaranteed to be a 64 bit number. If your compiler supports C99, you can use the uint64_t type, which is defined in stdint.h
To save the hex result we use a string, in the case of C language that is a char pointer. The biggest 64 bit number can be saved in 16-digit hexadecimal number. That's why we allocate space for 17 characters(16 value digits + the null terminator).
Keep in mind that we want to take the
remainder from the division in reversed order. We could write them in
normal order and then loop through all of them to reverse their
order. This will take one additional loop. Instead we write them in
reversed order and from there on we just read them normally. No
additional loops needed.
For that reason we move the pointer to the last position:
hex += 16;
We put the terminating null at the end and start the loop. Inside it we do the following:
The complete source code of this convertor is available in our GitHub repository.
Alternatively, you can download the source of the
complete example from here: dec-to-hex.zip
int main(void) { unsigned long decimal; char *hex; scanf("%lu", &decimal); hex = decimalToHex(decimal); printf("%lu in decimal equals %s in hexadecimal\n", decimal, hex); return 0; } char* decimalToHex(unsigned long decimal) { char *hex = (char*)malloc(17); if(hex == NULL) exit(1); hex += 16; *hex = '\0'; char remainder; while(decimal > 0) { --hex; remainder = remainderToHex(decimal % 16); *hex = remainder; decimal = decimal / 16; } return hex; }
And the result in the console looks like this:
I also prepared a tutorial for the reversed conversion: Hex to decimal, as well as others like Decimal to binary.