class Demo
{
public static void main(String[] args) {
toBin(60);
toOct(60);
toHex(60);
}
public static void toBin(int num) {
trans(num, 1, 1, "二进制");
}
public static void toOct(int num) {
trans(num, 7, 3, "八进制");
}
public static void toHex(int num) {
trans(num, 15, 4, "十六进制");
}
public static void trans(int num, int base, int offset, String name) {
System.out.print(name + ":");
char[] chs = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
'B', 'C', 'D', 'E', 'F' };
char[] arr = new char[32];
int pos = arr.length;
while (num != 0) {
int temp = num & base;
arr[--pos] = chs[temp];
num = num >>> offset;
}
for (int x = pos; x < arr.length; x++) {
System.out.print(arr[x]);
}
System.out.println();
}
}
Java 中的简易方式:
String bin = Integer.toBinaryString(35); //二进制 toBinaryString(int i)
//八进制 toOctalString(int i)
//十六进制 toHexString(int i)
System.out.println(bin);
int parseInt = Integer.parseInt(bin,2);
System.out.println(parseInt);