[ Team LiB ] |

## 2.6 Converting Between Decimal and Hexadecimal NumbersNN 2, IE 3 ## 2.6.1 ProblemYou want to change a decimal number to its hexadecimal equivalent, and vice versa. ## 2.6.2 SolutionWhile 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 var decimalVal = parseInt( For 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 DiscussionHexadecimal 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 var result = 0xff - 200; Hexadecimal digits The var decimalVal = parseInt("11010011", 2); ## 2.6.4 See AlsoRecipe 2.1 for converting between number and string value types. |

[ Team LiB ] |