A (More Bad-Ass) Base Converter
October 28th, 2014
Converts between the bases two through sixteen.
1) Enter a positive integer in the field below.
2) Select the base for the number entered.
3) Select the base to convert to.
4) Click “Convert” when ready.
Step 0: Set Up
To create the files you will need for this tutorial, you'll need some kind of text editor. My personal favorite is Sublime Text. This text editor will help make your code look pretty by colorizing the text against a dark background.
Step 1: The User Interface
The following code creates a simple user interface for interacting with the applet. It's a lime-green web form that takes in a number as input through a text field and converts it to and from various numerical bases. (The user selects the starting and ending bases through drop-down menus). To start the conversion, the user clicks on the "Convert" button. If the input data is correct (i.e. the input number is a valid number of the starting base), the calculator will display a result message at the bottom. If the input is invalid, the calculator will print an error message in the same place.
Copy and paste the following code into a text editor. Save the file as "baseConverter.html" in the "BaseConverter" folder you created in step zero.
Step 2: The Main Function
Open up a new file in your text editor. Copy and paste the code below into this file and save it as "functions.js" in your BaseConverter folder. The code below is the "main" function for the applet. The function is called when the user clicks the "Convert" button. Of course, there are more "helper" functions you will need to make this applet work, so read on!
Step 3: "Sanity Check" Functions
Good programmers know the importance of "sanity checks." An application should be able to handle all kinds of user input without crashing. The functions below "clean up" the text field input by removing space characters, setting letters to uppercase, and making sure that the number and starting base match. If they don't match up, the applet will display an error message.
Step 4: The Base-Conversion Logic
Finally, we need to add the functionality that performs the actual base conversion. The functions below convert a number from the starting base to decimal first. Then it converts that decimal value to the output base.