Thursday, July 9, 2009

Decimal to Hex and Hex to Decimal in JavaScript

Generally JavaScript doesn't have a particular data type or class for hex values but it still provides couple of features which will let you work with hex data.

In similar to Ruby you can keep your hex values in strings and the convert them into decimal values back and forth.

var hex = 'FF';

var dec = parseInt(hex, 16); // -> 255

dec = dec + 255;

hex = dec.toString(16); // -> '1ff'

No comments: