import java.util.Scanner;
class Demo1_Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = 0;
for (; ;) {
System.out.println("请输入一个整数:");
String str = sc.nextLine();
try {
x = Integer.parseInt(str);
break;
}
catch (Exception ex) {
System.out.println("数据录入错误!");
}
}
System.out.println("十进制:" + x);
Binary(x);
Octa(x);
Hex(x);
}
//进制转换输出
public static void arrary(int[] arr1) {
char[] arr = {'0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F'}; //定义输出形式模板
int count = 0;
for (int i = 0;i < arr1.length;i++ ) { //去除无效元素
if (arr1[i] == 0) {
count++;
}else {
break;
}
}
for (int i = count;i < arr1.length ;i++ ) {
System.out.print(arr[arr1[i]]); //调用模板并输出
if((i+1) % 4 == 0) {
System.out.print(" "); //控制输出格式
}
}
System.out.println(); //换行
}
//进制转换运算
public static int[] toOperation(int x,int num,int top) {
int[] arr1 = new int[32]; //定义int型数组
int key,pos = arr1.length - 1; //定义变量
for ( ;pos >= 0;pos--) { //定义循环
key = x & num; //进行位运算将有效位保留
arr1[pos] = key; //将有效数值传人自定义数组
x = x >> top; //通过位作除法运算
}
/*
for ( ;pos >= 0;pos-- ) {
key = x % (num + 1);
arr1[pos] = key;
x = x / (num + 1);
}
*/
return arr1; //将运算结果返回
}
//二进制Binary
public static void Binary(int x) { //定义二进制转换方法
int num = 1;
int top = 1;
System.out.print("二进制:");
arrary(toOperation(x,num,top)); //调用运算及输出方法
}
//八进制Octa
public static void Octa(int x) { //定义八进制转换方法
int num = 7;
int top = 3;
System.out.print("八进制:");
arrary(toOperation(x,num,top)); //调用运算及输出方法
}
//十六进制Hex
public static void Hex(int x) { //定义十六进制转换方法
int num = 15;
int top = 4;
System.out.print("十六进制:");
arrary(toOperation(x,num,top)); //调用运算及输出方法
}
} |
|