从数字转换为hexavigesimal字母?

Pur*_*ret 3 java

我正在尝试使用JExcel重新排序一些Excel列.我还需要找到对其他单元格的引用,然后重新映射它们以引用正确的单元格.我觉得我已经完成了很多艰苦的工作,但我遇到了绊脚石.

我在维基百科上找到了这个代码,与SO链接:

 public static String toBase26(int number){
        number = Math.abs(number);
        String converted = "";
        // Repeatedly divide the number by 26 and convert the
        // remainder into the appropriate letter.
        do
        {
            int remainder = number % 26;
            converted = (char)(remainder + 'A') + converted;
            number = (number - remainder) / 26;
        } while (number > 0);

        return converted;
    }
Run Code Online (Sandbox Code Playgroud)

但当我将数字35输入其中时,会发生以下情况:

  1. number = 35
  2. remainder = 9
  3. converted= char(9 +'A')+""= J.
  4. number =(35-9)/ 26 = 1
  5. 1> 0
  6. remainder = 1
  7. char(1+'A') = B.
  8. converted= char(1 +'A')+"J"= BJ

这是预期的方式,如基数10(35)=基数26(19).但我实际上想要参考专栏AJ.

我无法解释为了得到正确的信件我需要做出哪些改变.每当我尝试在纸上进行处理时,我最终都会破坏之前提取的字母.例如,我认为不会起作用,因为这意味着我remainder第一次以8 结束,然后将转换为I,除非我错过了什么?

任何有关这方面的帮助将不胜感激.我环顾四周,浪费了足够的时间.我只是想要一些帮助才能让它发挥作用.

Pat*_*shu 5

这背后"hexavidecimal系统"的绊脚石是,它有一个为0,但单位列跳过0,只有从AZ的范围内.考虑以下十进制转换:

A 1 (0*26 + 1)
...
Z 26 (0*26 + 26)
AA 27 (1*26 + 1)
...
AZ 52 (1*26 + 26)
BA 53 (2*26 + 1)
...
BZ 78 (2*26 + 26)
CA 79 (3*26 + 1)
...
ZZ 702 (26*26 + 26)
AAA 703 (1*26*26 + 1*26 + 1)
Run Code Online (Sandbox Code Playgroud)

看到问题?十六进制数中缺少"零":

00A 1
...
00Z 26
0AA 27
...
0AZ 52
0BA 53
...
0BZ 78
0CA 79
...
0ZZ 702 (26*26 + 26)
AAA 703 (1*26*26 + 1*26 + 1)
Run Code Online (Sandbox Code Playgroud)

但是,单位列永远不会有零!

显然我们不打印这些零,但它应该有助于你理解出了什么问题.


这是我们的算法.我在假设十进制0 =十六进制A,1 - > B,25 - > Z,26 - > AA等假设下编写算法,因为它使我更容易绕过头.如果这不是假设你想在运行代码前减去1 :)

0. If number =< 0, return.

1. Modulo by 26. Convert 0-25 to 'A'-'Z'. //This is our units column.

Loop {

    2. Divide the number by 26 (integer division rounding down).

    3. If number =< 0, return.

    4. Modulo by 26. Convert 0-25 to 'Z','A'-'Y'. //This is our next column (prepend to string output).

} 
Run Code Online (Sandbox Code Playgroud)

转换小数730 - > ABC hexavigesimal

模数为730乘以26 = 2 - >'C'为单位列

将730除以26 = 28

对于数十列,模数28乘26 = 2 - >'B'

将28除以26 = 1

模数1乘26 = 1 - >'A'表示数百列

除以1 = 26 = 0

数字为空,因此返回'ABC'