Last updated on Sep 10, 2020 by Suraj Sharma
In this tutorial, you will learn how you can convert a decimal number to a hexadecimal string and vice versa.
To convert a JavaScript Number to it’s hexadecimal, toString() method is used. toString()
method accepts a number parameter, ranging from 2 to 32, which specifies the base to use for representing the numeric values.
(234).toString(16) // "ea"
(-234).toString(16) // "-ea"
Converting a negative number to hexadecimal, results in negative hexadecimal.
To avoid negative hexadecimal, we can use the two’s complement hexadecimal representation of the negative number.
((-2)>>>0).toString(16) // "fffffffe"
We have used the zero-fill right shift >>> operator, which converts a negative number to an unsigned number
To convert a float to a hexadecimal requires you to first get the round value of the float and then use the toString
method with base 16 to get a hexadecimal string
(2.6).toString(16) // "2.999999999999a"
(Math.round(2.6)).toString(16) // "3"
To convert a hexadecimal string to a number, we use parseInt()
method with base 16 as a second parameter
parseInt('ea', 16) // 234
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.