Main Page

Introduction to Javascript


Decimal / hexadecimal conversion



Script

/**
 *  Converts decimal number to hexadecimal string.
 *  @method d2h
 *  @param  {int} d
 *  @return {mixed}   if d is a number then return hexadecimal string else return d
 */
function d2h(d)
{
  return (isNaN(d)) ? d : d.toString(16);
}

function doStrDec2Hex(input, output)
{
  var hexNum = d2h(parseInt(input.value));

  output.value = (typeof hexNum == "string") ? hexNum.toUpperCase() : input.value;
}

function doStrHex2Dec(input, output)
{
  output.value = h2d(input.value);
}

/**
 *  Converts hexadecimal string to decimal number.
 *  @method h2d
 *  @param {String} h
 *  @return {mixed}   if h can be parsed to int then return h as decimal int else return h
 */
function h2d(h)
{
  var n = parseInt(h, 16);

  return (isNaN(n)) ? h : n;
}