int num = 31;
String str_bin = toBinary(num);
System.out.println("bin="+str_bin);
String str_oct = toOctal(num);
System.out.println("oct=0"+str_oct);
String str_hex = toHex(num);
System.out.println("hex=0x"+str_hex);
}
//十进制转换十六进制
public static String toHex(int num) {
return trans(num,15,4);
}
//十进制转换八进制
public static String toOctal(int num) {
return trans(num,7,3);
}
//十进制转换二进制
public static String toBinary(int num) {
return trans(num,1,1);
}
public static String trans(int num,int base,int offset){
//建立表
char[] chs = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
char[] arr = new char[32]; //建立容器
int index = arr.length; //建立角标
while(num != 0){
int temp = num & base;
arr[--index] = chs[temp]; //根据&运算结果作为角标查表,获取对应的字符,并进行存储
num = num >>> offset;
}
return toString(arr,index);
}
public static String toString(char[] arr, int index) {
String temp = "";
for (int i = index; i < arr.length; i++) {
temp = temp + arr[i];
}
return temp;
}
|
|