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 x 161) + (15 x 160) = 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