How can I convert numbers to hexadecimal strings?
Although it was not mentioned in the original documentation for JavaScript 2.0, thetoString
method has been available for converting integers into strings since the release of Netscape Navigator 2.0. For example, if i is an integer, the statement
i = i . toString ();
changes it into a character string representing the same value.
In JavaScript 2.0, integer-to-string conversions using the toString
method were always performed in base 10. In JavaScript 3.0, however, an optional integer parameter can be supplied to specify a different radix. For example, the following program generates a character string s whose value is "101", the binary representation of the (decimal) number 5:
i = 5;
s = i . toString (2);
Unfortunately, if you are using the Windows 95 version of Netscape 3.01 or lower, there is a bug in the JavaScript interpreter that causes toString
to malfunction when the radix is greater than 10 and the integer being converted is supposed to result in a string containing one or more "a" characters. To be more specific, wherever a's are supposed to appear in the output string, for some strange reason colons (:) appear instead!
To illustrate, consider the decimal value 26. If you use toString (16)
to get its hexadecimal equivalent, you will not get "1a", but instead you will get "1:".
So far, I have diagnosed this bug on Windows and Unix versions of Netscape Navigator 3. It may exist on the Macintosh platforms as well. Unless you are sure that none of the visitors to your web site are using a browser that has this bug, you should avoid using the toString
method with a radix parameter greater than 10. (This bug will probably be fixed in Navigator 4.)
To see if your browser suffers from this bug, examine the following JavaScript output which was produced by your browser when you loaded this document:
dec hex dec hex dec hex dec hex --- --- --- --- --- --- --- ---If all the dec-to-hex conversions are correct, then your browser probably does not have the bug.
Charlton Rose
3 Jan. 1997