Shammer's Philosophy

My private adversaria

Java16進数演算 on String

Javaで16進数の計算を行いたい。でも、Hexadecimalというようなクラスはない。String/Integer/Doubleなどのようにあってほしかったが。
とりあえず、16進数の任意の値を文字列で受け取り、それを計算する例。

public class Hexadecimal {
    private static final char[] HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    private static final int convertHexString2Integer(String s){
	double result = 0;
	char[] array = s.toCharArray();
	double base = Math.pow(16, (array.length - 1));
	for( int i = 0 ; i < array.length ; i++ ){
	    for( int j = 0 ; j < HEX.length ; j++ ){
		if( Character.toUpperCase(array[i]) == HEX[j] ){
		    result = result + (base * j);
		}
	    }
	    base = base / 16;
	}
	return new Double(result).intValue();
    }
    private static final String nextValue(String s){
	return Integer.toHexString(1 + convertHexString2Integer(s)).toUpperCase();
    }
    public static void main(String[]args){
	System.out.println("The next value of 0x" + args[0] + " is " + nextValue(args[0]) + ".");
    }
}

実行例は以下。

$ java Hexadecimal 0
The next value of 0x0 is 1.
$ java Hexadecimal 1
The next value of 0x1 is 2.
$ java Hexadecimal 2
The next value of 0x2 is 3.
$ java Hexadecimal 3
The next value of 0x3 is 4.
$ java Hexadecimal 4
The next value of 0x4 is 5.
$ java Hexadecimal 5
The next value of 0x5 is 6.
$ java Hexadecimal 6
The next value of 0x6 is 7.
$ java Hexadecimal 7
The next value of 0x7 is 8.
$ java Hexadecimal 8
The next value of 0x8 is 9.
$ java Hexadecimal 9
The next value of 0x9 is A.
$ java Hexadecimal A
The next value of 0xA is B.
$ java Hexadecimal B
The next value of 0xB is C.
$ java Hexadecimal C
The next value of 0xC is D.
$ java Hexadecimal D
The next value of 0xD is E.
$ java Hexadecimal E
The next value of 0xE is F.
$ java Hexadecimal F
The next value of 0xF is 10.
$ java Hexadecimal 10
The next value of 0x10 is 11.
$