Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 707
forgetfulbur Avatar asked Jan 19 '17 03:01

forgetfulbur


People also ask

How do you convert numbers to alphabets in Python?

Use the chr() function to convert a number to a letter, e.g. letter = chr(97) . The chr() function takes an integer that represents a Unicode code point and returns the corresponding character.

How do you convert int to letter in Java?

An integer can be converted into a character in Java using various methods. Some of these methods for converting int to char in Java are: using typecasting, using toString() method, using forDigit() method, and by adding '0'.


1 Answers

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

like image 181
4castle Avatar answered Sep 30 '22 10:09

4castle