Advertisement
Advertisement


How to convert decimal to hexadecimal in JavaScript


Question

How do you convert decimal values to their hexadecimal equivalent in JavaScript?

2019/04/12
1
1511
4/12/2019 12:23:53 PM

Accepted Answer

Convert a number to a hexadecimal string with:

hexString = yourNumber.toString(16);

And reverse the process with:

yourNumber = parseInt(hexString, 16);
2019/04/12
2531
4/12/2019 12:24:17 PM

If you need to handle things like bit fields or 32-bit colors, then you need to deal with signed numbers. The JavaScript function toString(16) will return a negative hexadecimal number which is usually not what you want. This function does some crazy addition to make it a positive number.

function decimalToHexString(number)
{
  if (number < 0)
  {
    number = 0xFFFFFFFF + number + 1;
  }

  return number.toString(16).toUpperCase();
}

console.log(decimalToHexString(27));
console.log(decimalToHexString(48.6));

2019/04/12

The code below will convert the decimal value d to hexadecimal. It also allows you to add padding to the hexadecimal result. So 0 will become 00 by default.

function decimalToHex(d, padding) {
    var hex = Number(d).toString(16);
    padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;

    while (hex.length < padding) {
        hex = "0" + hex;
    }

    return hex;
}
2019/04/12

function toHex(d) {
    return  ("0"+(Number(d).toString(16))).slice(-2).toUpperCase()
}
2012/11/05

For completeness, if you want the two's-complement hexadecimal representation of a negative number, you can use the zero-fill-right shift >>> operator. For instance:

> (-1).toString(16)
"-1"

> ((-2)>>>0).toString(16)
"fffffffe"

There is however one limitation: JavaScript bitwise operators treat their operands as a sequence of 32 bits, that is, you get the 32-bits two's complement.

2019/09/12

With padding:

function dec2hex(i) {
   return (i+0x10000).toString(16).substr(-4).toUpperCase();
}
2011/07/13

Source: https://stackoverflow.com/questions/57803
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]