Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions

  




 

 

The JavaScript FAQ
Prev Home Next

Converting Numbers to Another Base

Question: How do I convert a number to a different base (radix)?

Answer: In JavaScript 1.1, you can use the standard method Number.toString(radix) for converting a number to a string representing that number in a non-decimal number system (e.g. to a string of binary, octal or hexadecimal digits). For example:

a = (32767).toString(16)  // this gives "7fff"
b = (255).toString(8)     // this gives "377"
c = (1295).toString(36)   // this gives "zz"
d = (127).toString(2)     // this gives "1111111"

However, in old browsers (supporting only JavaScript 1.0) there is 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:

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

The JavaScript FAQ
Prev Home Next


 
 
  Mirrored with kind permission of Alexei Kourbatov Design by Interspire