⼗六进制转⼋进制(JAVA)
思路:
先将16进制转成⼆进制,再把⼆进制转成8进制,需要⽤到java  Integer的 toBinaryString 和toOctalString⽅法。还涉及到补位通过取余进⾏⼿动补充。写了两个⽅法。此外还有先导零,我们需要在输出的时候,先判断从k!=0的时候开始截取,代码如下:
import java.util.Scanner;
public class sixteen {
public static void main(String[] args) {
//获取输⼊
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
//获取每⼀⾏输⼊的数据
String line = sc.next();
StringBuilder builder = new StringBuilder();
for (int k = 0; k < line.length(); k++) {
//取每⼀位⼗六进制转换为⼆进制放到容器⾥边
builder.append(hexToBin(line.substring(k, k + 1)));
}
String bin = String());
builder = new StringBuilder();
for (int k = 0; k < bin.length(); k += 3) {
java valueofbuilder.append(binToOct(bin.substring(k,k+3)));
}
String result = String();
for (int k=0;k<result.length();k++){
if(result.charAt(k) !='0'){
result = result.substring(k);
break;
}
}
System.out.println(result);
}
}
/
/16进制转⼆进制
static String hexToBin(String hex) {
return BinaryString(Integer.valueOf(hex, 16)));    }
//⼆进制转8进制
static String binToOct(String bin) {
OctalString(Integer.valueOf(bin, 2));
}
//8进制补零
static String format3(String str) {
if (str.length() % 3 == 2) {
str = "0" + str;
}
if (str.length() % 3 == 1) {
str = "00" + str;
}
return str;
}
//16进制转2进制补零
static String format4(String str) {
if (str.length() % 4 == 3) {
str = "0" + str;
}
if (str.length() % 4 == 2) {
str = "00" + str;
}
if (str.length() % 4 == 1) {
str = "000" + str;
}
return str;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。