Created
November 23, 2016 16:04
-
-
Save agirorn/0e740d012b620968225de58859ccef5c to your computer and use it in GitHub Desktop.
Convert decimal to hex in JavaScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function dec2hexString(dec) { | |
return '0x' + (dec+0x10000).toString(16).substr(-4).toUpperCase(); | |
} |
I think it solution better
intToHex(integer) {
let number = (+d).toString(16).toUpperCase()
if( (number.length % 2) > 0 ) { number= "0" + number }
return number
}
I believe you can do something like this as well:
(n).toString(16).padStart(6, '0').toUpperCase()
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
Nice code!
But this code can only handle numbers not bigger than
65535
.JavaScript already offers a "native way" of doing it:
However, the example above can only handle numbers till Number.MAX_SAFE_INTEGER => 9007199254740991
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