Hexadecimal (or hex for short) is a number system that uses 16 symbols to represent numbers. The symbols are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F. Each symbol corresponds to a value from 0 to 15. For example, A is 10, B is 11, and F is 15.
Hex numbers are often used in computer science and programming because they can represent binary numbers more compactly and conveniently. For example, the binary number 1010 0010 0011
can be written as A23
in hex.
Decimal is a number system that uses 10 symbols to represent numbers. The symbols are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9, corresponds to a value from 0 to 9.
To convert a hex number to a decimal number in JavaScript, you can use the parseInt()
function.
parseInt(string)
parseInt(string, radix)
This function takes two arguments: a string and a radix. The string is the hex number you want to convert, and the radix is the base of the number system you want to convert to. In this case, the radix is 16 for hex and 10 for decimal.
For example, if you want to convert the hex number FF
to decimal, you can write:
console.log(parseInt("FF", 16)); // 255
Because FF
in hex is equal to $(15 * 16^1) + (15 * 16^0) = (240) + (15) = 255$ in decimal.
Here are some more examples:
console.log(parseInt("2", 16)); // 2
console.log(parseInt("35", 16)); // 53
console.log(parseInt("1f4", 16)); // 500
console.log(parseInt("7b2", 16)); // 1970
console.log(parseInt("123abc", 16)); // 1194684
To convert a decimal number to a hex number, you can use the toString()
method of the Number object. This method takes a parameter called radix, which specifies the base of the converted string. For hexadecimal, the radix is 16.
var decimalNumber = 255;
var hexNumber = decimalNumber.toString(16);
console.log(hexNumber); // ff
Let $H$ represent the hex number, and let $d_{n}, d_{n-1}, \ldots, d_{2}, d_{1},$ and $d_{0}$ represent its individual digits from left to right.
The decimal equivalent ($D$) of the hex number $H$ can be calculated using the formula:
In this formula:
So, the decimal equivalent is calculated by multiplying each digit by the corresponding power of 16 and summing up these products.
For example, to convert the hex number $1A$ to decimal:
Converting a decimal number to hex involves dividing the decimal number by 16 repeatedly and keeping track of the remainders at each step. The remainders are then converted to their corresponding hex digits.
Let $D$ represent the decimal number to convert, and let $R$ represent the remainders obtained during the process.
For example, let’s convert the decimal number $305$ to hex:
$R_{1} = 305 \mod 16 = 1$
$Q_{1} = \left\lfloor \frac{305}{16} \right\rfloor = 19$
Continue the process:
Reading the remainders in reverse order: $131$.
So, the decimal number $305$ is equivalent to the hexadecimal number $131$.