Skip to content

Instantly share code, notes, and snippets.

@agirorn
Created November 23, 2016 16:04
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agirorn/0e740d012b620968225de58859ccef5c to your computer and use it in GitHub Desktop.
Save agirorn/0e740d012b620968225de58859ccef5c to your computer and use it in GitHub Desktop.
Convert decimal to hex in JavaScript.
function dec2hexString(dec) {
return '0x' + (dec+0x10000).toString(16).substr(-4).toUpperCase();
}
Copy link

ghost commented Jul 30, 2018

Nice code!

But this code can only handle numbers not bigger than 65535.

dec2hexString(65535)
// => "0xFFFF"
dec2hexString(65536)
// => "0x0000"
dec2hexString(65537)
// => "0x0001"

JavaScript already offers a "native way" of doing it:

// our decimal number
const nr = 999999999;

// convert to hex
const hex = nr.toString(16);

// back to dec:
const decNr = parseInt(hex, 16);

However, the example above can only handle numbers till Number.MAX_SAFE_INTEGER => 9007199254740991

const converter = require('hex2dec');

const hex = converter.decToHex("90071992547409919007199254740991"); // bigger than 9007199254740991
const dec = converter.hexToDec(hex); // => "90071992547409919007199254740991"

You have to use arrays if you still need bigger numbers :

detail explaination: http://www.danvk.org/wp/2012-01-20/accurate-hexadecimal-to-decimal-conversion-in-javascript/index.html
live demo: http://www.danvk.org/hex2dec.html
npm package: https://www.npmjs.com/package/hex2dec

@MairwunNx
Copy link

@rajmondsolique hmm const hex = nr.toString(16); not normal :(

image

image

@MairwunNx
Copy link

I think it solution better

intToHex(integer) {
      let number = (+d).toString(16).toUpperCase()
      if( (number.length % 2) > 0 ) { number= "0" + number }
      return number
}

@nullhook
Copy link

I believe you can do something like this as well:
(n).toString(16).padStart(6, '0').toUpperCase()

@kenshin1102
Copy link

kenshin1102 commented Jan 20, 2021

export const numberToHex = number => {
  const HEX = 16;
  return Number(number).toString(HEX).toUpperCase()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment