Last active
November 14, 2017 02:02
-
-
Save elycruz/3d27458e1fd2bd4d9c7b to your computer and use it in GitHub Desktop.
Javascript number to hexadecimal string function.
This file contains 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
/** | |
* 'Fast Remainder' method for number to hex. | |
* @see http://www.wikihow.com/Convert-from-Decimal-to-Hexadecimal (fast remainder method (method 2)). | |
*/ | |
const hexMap = [ | |
[0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [5, 5], | |
[6, 6], [7, 7], [8, 8], [9, 9], [10, 'A'], [11, 'B'], | |
[12, 'C'], [13, 'D'], [14, 'E'], [15, 'F'] | |
]; | |
function numToHex (d) { | |
var q, | |
r, | |
a = [], | |
out = '0x'; | |
do { | |
q = parseInt(d / 16, 10); | |
r = d - (q * 16); | |
a.push(hexMap[r][1]); | |
d = q; | |
} | |
while (q > 0); | |
for (var i = a.length - 1; i >= 0; i -= 1) { | |
out += a[i]; | |
} | |
return out; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment