public class ConvertTest2 {
public static void main(String[] args) {
int val = 28;
System.out.println("要进行转换的十进制数为: "+val);
decimalToHex(val);
decimalToBinary(val);
decimalToOctal(val);
}
public static void decimalToHex(int x) {
transform(x,15,4);
}
public static void decimalToBinary(int x) {
transform(x,1,1);
}
public static void decimalToOctal(int x) {
transform(x,7,3);
}
public static void transform(int x, int base, int offset) {
if (x == 0) {
System.out.println("0");
return;
}
char[] hextab = {'0','1','2','3',
'4','5','6','7',
'8','9','A','B',
'C','D','E','F'};
char[] rslt = new char[32];
int pos = rslt.length;
while (x!=0) {
int xor = x & base;
rslt[pos-1] = hextab[xor];
pos--;
x = x >>> offset;
}
if (base == 15) {
System.out.print("-> 转换后的十六进制数为: ");
}else if(base == 1){
System.out.print("-> 转换后的二进制数为: ");
}else if(base == 7){
System.out.print("-> 转换后的八进制数为: ");
}
for (int i = pos; i < rslt.length; i++) {
System.out.print(rslt[i]);
}
System.out.println();
}
}
JAVA小练习-进制转换2
最新推荐文章于 2024-11-15 18:38:47 发布