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.
Advertise on this site. I promise you will like the rates :)
|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:
And the result in the console looks like this: