计算没有字母的更高的碱基

Counting in bases higher which don't have letters attached to them

大家好 Whosebugers,今天我提出了一个奇怪的问题。

众所周知,有不同的计数方式(根据碱基)

对于基数 2(a.k.a 二进制),一个数如下

0000 = (2^3 x 0) + (2^2 x 0) + (2^1 x 0) + (2^0 x 0) = 0

0001 = (2^3 x 0) + (2^2 x 0) + (2^1 x 0) + (2^0 x 1) = 1

0010 = (2^3 x 0) + (2^2 x 0) + (2^1 x 1) + (2^0 x 0) = 2

0011 = (2^3 x 0) + (2^2 x 0) + (2^1 x 1) + (2^0 x 1) = 3

...等等...


当我们达到高于 10 的基数时,例如 16(a.k.a 十六进制)我们使用字母来表示值:

例如:

200 base 16 = C8 ---> http://www.binaryhexconverter.com/decimal-to-hex-converter(如果你不相信我的话 ;))


但是,我们如何计算高于字母允许的碱基数? (基数 37+)

我写了一个简单的java程序来说明我的观点:

public class Testing {
public static void main(String[] args) {
    for (int base = 1;base<=50;base++){
        System.out.println("===========================Base " + base + "===============================");
        for (int value=1; value<=50; value++){
              System.out.println(value + " base " + base + " is equal to: " + Integer.toString(value, base));
            }
        }
    }
}

以下是我的程序输出的一些片段:

40 base 36 is equal to: 14
41 base 36 is equal to: 15
42 base 36 is equal to: 16
43 base 36 is equal to: 17
44 base 36 is equal to: 18
45 base 36 is equal to: 19
46 base 36 is equal to: 1a
47 base 36 is equal to: 1b
48 base 36 is equal to: 1c
49 base 36 is equal to: 1d
50 base 36 is equal to: 1e

28 base 37 is equal to: 28
29 base 37 is equal to: 29
30 base 37 is equal to: 30
31 base 37 is equal to: 31
32 base 37 is equal to: 32
33 base 37 is equal to: 33
34 base 37 is equal to: 34
35 base 37 is equal to: 35
36 base 37 is equal to: 36
37 base 37 is equal to: 37
38 base 37 is equal to: 38
39 base 37 is equal to: 39
40 base 37 is equal to: 40
41 base 37 is equal to: 41
42 base 37 is equal to: 42
43 base 37 is equal to: 43
44 base 37 is equal to: 44
45 base 37 is equal to: 45
46 base 37 is equal to: 46
47 base 37 is equal to: 47
48 base 37 is equal to: 48
49 base 37 is equal to: 49
50 base 37 is equal to: 50

如您所见,base 37+ 不起作用。

有办法解决这个问题吗?谢谢!

Character.MAX_RADIX 等于 36(10 位数字和 26 个字母)。

如果你想为基数使用更高的值,你将不得不编写你自己的方法。这应该不会太难。我建议修改 Integer.toString(int, int) 的源代码。此方法的代码使用此数组:

final static char[] digits = {
    '0' , '1' , '2' , '3' , '4' , '5' ,
    '6' , '7' , '8' , '9' , 'a' , 'b' ,
    'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
    'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
    'o' , 'p' , 'q' , 'r' , 's' , 't' ,
    'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};

试试这个。

public static String DIGITS = "0123456789abcdefghijklmnopqrstuvwxyz@!#$%&;:";

public static String toString(int i, int base) {
    StringBuilder sb = new StringBuilder();
    for (; i > 0; i /= base)
        sb.append(DIGITS.charAt(i % base));
    if (sb.length() == 0)
        sb.append(0);
    return sb.reverse().toString();
}