嘿,我的教授希望手动将二进制转换为十六进制,而不使用java中的toHex或toBinary()等内置函数,我想我找到了一种使用字符串将bin转换为十六进制的很酷的方式
StringBuffer psd = new StringBuffer();
int binary = 0;
System.out.println("Enter a Binary number to be converted.");
System.out.println("Format: xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx");
Scanner keyboard = new Scanner(System.in);
String x = keyboard.nextLine().replaceAll(" ", "/"); ///.trim().replaceAll(" ", "/");
Scanner seperate = new Scanner(x).useDelimiter("/");
//10 System.out.println(x);
// System.out.println(seperate);
while(seperate.hasNext()){
String s1 = seperate.next();
// binary = Integer.parseInt(s1);
String HexString = null;
//int binary = 1010;
switch (s1){
case 0001: HexString = "1";
psd.append(HexString);
break;
case 0010: HexString = "2";
psd.append(HexString);
break;
case 0011: HexString = "3";
psd.append(HexString);
break;
case 0100: HexString = "4";
psd.append(HexString);
break;
case 0101: HexString = "5";
psd.append(HexString);
break;
case 0110: HexString = "6";
psd.append(HexString);
break;
case 0111: HexString = "7";
psd.append(HexString);
break;
case 1000: HexString = "8";
psd.append(HexString);
break;
case 1001: HexString = "9";
psd.append(HexString);
break;
case 1010: HexString = "A";
psd.append(HexString);
break;
case 1011: HexString = "B";
psd.append(HexString);
break;
case 1100: HexString = "C";
psd.append(HexString);
break;
case 1101: HexString = "D";
psd.append(HexString);
break;
case 1110: HexString = "E";
psd.append(HexString);
break;
case 1111: HexString = "F";
psd.append(HexString);
break;
//StringBuffer psd = new StringBuffer();
//System.out.println(psd);
}
//System.out.println(binary);
//System.out.println(psd);
System.out.println(s1);
}
// System.out.println(binary);
System.out.println(psd);
//System.out.println(binary);
}
基本上一切都有效但是有一个前导零的情况 0110 0111 0101 ......它不会更新变量 但是当它分析有领先的情况时,它会分别转换它 有人可以帮我解决我做错了什么。 提前谢谢。