Converting Numbers to Another BaseQuestion: How do I convert a number to a different base (radix)?
Answer:
In JavaScript 1.1, you can use the standard method a = (32767).toString(16) // result: "7fff" b = (255).toString(8) // result: "377" c = (1295).toString(36) // result: "zz" d = (127).toString(2) // result: "1111111" However, in very old browsers (supporting only JavaScript 1.0) there was no standard method for this conversion. Here is a function that does the conversion of integers to an arbitrary base (radix) in JavaScript 1.0: function toRadix(N,radix) {
var HexN="", Q=Math.floor(Math.abs(N)), R;
while (true) {
R=Q%radix;
HexN = "0123456789abcdefghijklmnopqrstuvwxyz".charAt(R)
+ HexN;
Q=(Q-R)/radix;
if (Q==0) break;
}
return ((N<0) ? "-"+HexN : HexN);
}
You can test this conversion right now: |
Copyright © 1999-2012, JavaScripter.net.