javatostringbase-conversion

Base 26 as alphabetic using Java's Integer.toString()


So I just learned Integer.toString(int x, int radix); and thought it was pretty awesome since it makes base conversions super easy.

However, I'm trying to write with Base-26 phonetically (a - z) and noticed that Integer.toString() follows hexadecimal's example in that it begins numerically and then uses the alphabet (0 - p).

I already know how to do convert to Base-26 by hand, I don't need that code. But I'm wondering if there's a way to take advantage of Integer.toString() since it's pretty much already done all the heavy lifting.

Any ideas?


Solution

  • You can iterate over a char[] to shift the output from Integer.toString into the range you want.

    public static String toAlphabeticRadix(int num) {
        char[] str = Integer.toString(num, 26).toCharArray();
        for (int i = 0; i < str.length; i++) {
            str[i] += str[i] > '9' ? 10 : 49;
        }
        return new String(str);
    }
    

    Ideone Demo