How to convert decimal to hexadecimal in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

The number class has a toString method that accepts base as argument. We can pass base 16(hex numbers) to get the desired number converted to hexadecimal string.

Example

console.log(Number(255).toString(16))
console.log(Number(17).toString(16))

Output

ff
11

We can convert these numbers back to decimal using the parseInt function. The parseInt function available in JavaScript has the following signature −

parseInt(string, radix);

Where, the paramters are the following

string −The value to parse. If this argument is not a string, then it is converted to one using the ToString method. Leading whitespace in this argument is ignored.

radix −An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string.

So we can pass the string and the radix and convert any numbner with base from 2 to 36 to integer using this method.

Example

console.log(parseInt("ff", 16))
console.log(parseInt("11", 16))

Output

255
17
raja
Published on 18-Sep-2019 13:58:13
Advertisements