How do you convert decimal values to their hexadecimal equivalent in JavaScript?
As the accepted answer states, the easiest way to convert from decimal to hexadecimal is var hex = dec.toString(16)
. However, you may prefer to add a string conversion, as it ensures that string representations like "12".toString(16)
work correctly.
// Avoids a hard-to-track-down bug by returning `c` instead of `12`
(+"12").toString(16);
To reverse the process you may also use the solution below, as it is even shorter.
var dec = +("0x" + hex);
It seems to be slower in Google Chrome and Firefox, but is significantly faster in Opera. See http://jsperf.com/hex-to-dec.