Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Math processing
Expertise: Beginner
Mar 19, 1997




How can I convert numbers to hexadecimal strings?

How can I convert numbers to hexadecimal strings?

Although it was not mentioned in the original documentation for JavaScript, the toString 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 an earlier version of JavaScript, integer-to-string conversions using the toString method were always performed in base 10. In the latest version of JavaScript, 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 "1:".

It is very likely that this bug is isolated to the Windows 95 versions of Netscape. However, problems created by this bug are more widespread: Regardless of your own Web-surfing platform, unless you are sure that none of the visitors to your Web pages are using Windows 95 (highly unlikely, needless to say), you should not use the toString method with a radix parameter greater than 10.

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, your browser probably does not have the bug.
DevX Pro
Comment and Contribute








