2.6 Converting Between Decimal and Hexadecimal Numbers
NN 2, IE 3
2.6.1 Problem
You want to
change a decimal number to its hexadecimal equivalent, and vice
versa.
2.6.2 Solution
While the core JavaScript language provides facilities for going from
hexadecimal to decimal, you need a custom function to go the other
way.
To get a hexadecimal number as a string into its decimal equivalent,
use the parseInt( ) method and specify the second
parameter as 16:
var decimalVal = parseInt(myHexNumberValue, 16);
For myHexNumberValue, you can use either
the hexadecimal characters for the number, or the format required for
hexadecimal arithmetic in JavaScript: the hexadecimal characters
preceded by 0x or 0X (a zero
followed by an X). Here are some examples with string literals in the
two formats:
var decimalVal = parseInt("1f", 16);
var decimalVal = parseInt("0x1f", 16);
To convert a decimal number (between 0 and 255) to a hexadecimal
string equivalent, use the following function:
function dec2Hex(dec) {
dec = parseInt(dec, 10);
if (!isNaN(dec)) {
hexChars = "0123456789ABCDEF";
if (dec > 255) {
return "Out of Range";
}
var i = dec % 16;
var j = (dec - i) / 16;
result = "0x";
result += hexChars.charAt(j) + hexChars.charAt(i);
return result;
} else {
return NaN;
}
}
Because JavaScript automatically converts hexadecimal numbers to
their decimal equivalents for arithmetic operations, the hexadecimal
conversion is needed only for display of a hexadecimal result.
2.6.3 Discussion
Hexadecimal arithmetic isn't used much in
JavaScript, but the language provides rudimentary support for base 16
numbers. As long as you signify a hexadecimal number value with the
leading 0x, you can perform regular arithmetic on
that value to your heart's content. But be aware
that the results of those operations are returned in base 10, which
allows the odd possibility of using hexadecimal and decimal values in
the same expression:
var result = 0xff - 200;
Hexadecimal digits a through f
may be expressed in your choice of upper- or lowercase letters.
The parseInt( ) method is frequently a handy tool
for getting values in other bases into decimal. For example, you
obtain a decimal equivalent of a binary number string by specifying
base 2 as the second argument of the method:
var decimalVal = parseInt("11010011", 2);
2.6.4 See Also
Recipe 2.1 for converting between number and string value types.
|