10

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?

forgetfulbur
  • 103
  • 1
  • 7

4 Answers4

8

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

4castle
  • 32,613
  • 11
  • 69
  • 106
0

No; the way that this method is implemented effectively guarantees that it starts from 0-9, then proceeds through a-f, then carries on should the radix exceed 16.

If you want to do this in your own way, then you will need to perform the offsets yourself.

Makoto
  • 104,088
  • 27
  • 192
  • 230
  • I figured this was the case. Any clever ways to perform the offsets to the already converted data? Other than the brute force way, of course. – forgetfulbur Jan 19 '17 at 03:50
  • A `char` can be added to, so if you wanted to define `'A'` or `'a'` as 0, then the offsets become straightforward to work with. – Makoto Jan 19 '17 at 05:16
0

if you want to have 26 = aa rather than ba then here's some code you can use.
This is a modification of the code 4castle posted to this thread.

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) - (num > 25 && i < 1 ? 1 : 0);
    }
    return new String(str);
}
0

This is Scala, but it does what you want with the correct flow over from Z to AA, and ZZ to AAA. The java code in previous examples is buggy and only counts to Y, not Z.

The important thing is to start counting from 1, not zero. This system for counting has no "0".

  def gen_symbols: LazyList[String] = LazyList.from(1).map { i_ =>
    val buf = new java.lang.StringBuffer
    var i = i_
    while (i > 0) {
      val rem = (i - 1) % 26
      buf.append(('A' + rem).toChar)
      i = (i - rem) / 26
    }
    buf.reverse.toString
  }
fommil
  • 5,757
  • 8
  • 41
  • 81