CatTail
11/30/2012 - 10:49 AM

Javascript: convert decimal into hexadecimal

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);
};