class="java" name="code">
private static final char[] chs = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
public static String toHexString(int x) {
return convert(x, 4);
}
public static String toOctalString(int x) {
return convert(x, 3);
}
public static String toBinaryString(int x) {
return convert(x, 1);
}
private static String convert(int x, int shift) {
int mask = (1 << shift) - 1;
char[] result = new char[32];
int pos = 32;
do {
result[--pos] = chs[x & mask];
x >>>= shift;
} while (x != 0);
// 起始偏移位置:pos表示当前索引位置
// 偏移数:32-pos表示最后一位索引位置-当前索引位置+1,即总长度-当前索引位置
return new String(result, pos, 32 - pos);
}
测试
System.out.println(toBinaryString(-23423));
System.out.println(Integer.toBinaryString(-23423));
System.out.println(toOctalString(21321));
System.out.println(Integer.toOctalString(21321));
System.out.println(toHexString(21321));
System.out.println(Integer.toHexString(21321));