Skip to content

Instantly share code, notes, and snippets.

@CatTail
Created November 30, 2012 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CatTail/4175093 to your computer and use it in GitHub Desktop.
Save CatTail/4175093 to your computer and use it in GitHub Desktop.
Javascript: convert decimal into hexadecimal
/**
* @param {number} dec Decimal number need to be converted
* @return {string} String representation of hexadecimal
*/
var dec2hex = function(dec) {
var buf = [],
map = '0123456789ABCDEF';
while (parseInt(dec / 16, 10) !== 0) {
buf.unshift(map[dec % 16]);
dec = parseInt(dec / 16, 10);
}
buf.unshift(map[dec % 16]);
return buf.join('');
};
var dec2hex2 = function(dec) {
var hex = [],
HEX = '0123456789ABCDEF';
do {
hex.unshift(HEX[dec & 0xF]);
} while ( (dec = dec >> 4) !== 0 );
return hex.join('');
};
var dec2hex3 = function(dec) {
return dec.toString(16);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment