brentonstrine brentonstrine - 3 years ago 298
Javascript Question

Working with hex strings and hex values more easily in Javascript

I am taking strings which represent hexadecimal numbers (actually, hex colors) and adding them. So, adding

. My method seems unnecessarily long and complicated:

var hexValue = "aaaaaa";
hexValue = "0x" + hexValue;
hexValue = parseInt(hexValue , 16);
hexValue = hexValue + 0x010101;
hexValue = hexValue.toString(16);
document.write(hexValue); // outputs 'ababab'

The hex value is still a string after concatenating
, so then I have to change it to a number, then I can add, then I have to change it back into hex format! There are even more steps if the number I'm adding to it is a hexadecimal string to begin with as well, or if you take into consideration that I am removing the
from the hex color before all this starts.

Surely there's a way to do this with less steps! (And I don't mean just putting it all on one line
or using shorthand, I mean actually doing less operations.)

Is there some way to get Javascript to stop using decimal for all of its mathematical operations and use hex instead? Or is there some other method of making Javascript work with Hex more easily?

Answer Source

No, there is no way to tell the JavaScript language to use hex integer format instead of decimal by default. Your code is about as concise as it gets but note that you do not need to prepend the "0x" base indicator when you use "parseInt" with a base.

Here is how I would approach your problem:

function addHexColor(c1, c2) {
  var hexStr = (parseInt(c1, 16) + parseInt(c2, 16)).toString(16);
  while (hexStr.length < 6) { hexStr = '0' + hexStr; } // Zero pad.
  return hexStr;

addHexColor('aaaaaa', '010101'); // => 'ababab'
addHexColor('010101', '010101'); // => '020202'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download