Skip to content

Instantly share code, notes, and snippets.

@elycruz
Last active November 14, 2017 02:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elycruz/3d27458e1fd2bd4d9c7b to your computer and use it in GitHub Desktop.
Save elycruz/3d27458e1fd2bd4d9c7b to your computer and use it in GitHub Desktop.
Javascript number to hexadecimal string function.
/**
* '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