Convert Number to Hexadecimal string
To convert a number to a hexadecimal string, you can use the toString() number method and pass 16 as the argument to the method in JavaScript.
const num = 1234;
const hexaDecimalString = num.toString(16);
console.log(hexaDecimalString); // "4d2"
- The
toString()method returns the hexadecimal value as astring. - The argument
16in thetoString()method is the radix.
Convert Hexadecimal string to a Number
Now to convert a hexadecimal string to a number, you can use the parseInt() number method and pass the hexadecimal string as the first argument and also the value16 as the second argument to the method in JavaScript.
/* Convert Hexadecimal String to Number */
const hexaDecimalString = "4d2";
const num = parseInt(hexaDecimalString, 16);
console.log(num); // 1234
- The
parseInt()method returns the corresponding number value. - The second argument
16in theparseInt()method is the radix.
See both examples live in JSBin.
That's it! 🌟