Way back in 2010 when I was getting my late-in-life bachelors degree, I needed to be able to calculate between two base numbers. I wrote a whole blog post about it here, if interested. Well, I ran across that code again, cleaned it up and hosted it. More on that in a minute. First, the concept…
We typically work in base-10, that is our number goes from 0 to 9, then we start over with zero again, incrementing the next position…
And you probably know that in computers, hexadecimal or, base-16 is used a lot. That is the same concept, but that goes 0 to 16. What do you do when you run out of numbers? You switch to letters, of course! Then when you reach the 16th value 9, plus 6 letters – F, THEN you start back at zero, and increment the next position:
And finally, in computers, you also see a lot of use of binary, or base-2. That is where you only have on and off, or zero and one. This is the same concept except as soon as you reach 1, it’s time to go back to 0 again, and increment the next position.
Well, I had an exam on this and had to have a good grasp on how this worked. So what did I do? I wrote a program to calculate between the different base values, or “radix”. I happened to stumble across the directory where this code was. I looked it over, cringed, and then decided to write it properly – or at least clean it up.
Now, it fully supports from base-2 to base-36, the maximum value. Why is that the maximum? Because that base includes all of the letters and the all of the numbers. You’d have to start going into special characters after that! Even so, it’s still not an issue because a base-36 can hold an extremely large number anyway so it’s no where close to being a problem! See the example below, the decimal number 1,234,567,890,987,654,321 is a simple 12-character value in base-36: 9DO1DJHJPEI9
The source code:
I went over this source code and broke it up into more appropriate chunks. You can download all of the files from this gist:
The biggest issue was working with numbers than have letters. I could easily generate that sort of output, but how do you parse input like that? Well, rather than reinventing the wheel, I got some code from http://rosettacode.org/wiki/Non-decimal_radices/Convert which does a string-to-number and number-to-string conversion.
So, once I have a value in numeric form, I can then convert it to the new radix and output it. For example, see here:
if the number is greater than nine, we must be in a radix which is greater than base-10. This means we need to start using letters. To do this, we look at a good ol’ ASCII chart:
as you can see, the letter A is ASCII decimal 65, so we use this to calculate what the letter value should be. As I was cleaning up old folders, I thought I’d go off on a tangent and post this code, so that I can delete this directory!