gpt4 book ai didi

java - 十六进制转二进制——java

转载 作者:行者123 更新时间:2023-12-02 01:49:38 31 4
gpt4 key购买 nike

我正在尝试从十六进制转换为二进制。我已经有了十进制转换为二进制的代码,只是不知道如何从那里转换为二进制。

public static String hexToDec(String valueIn) {
int endNum = 0;

for (int i = 0; i < valueIn.length(); i++) {
char curDigit = valueIn.charAt(i);
endNum *= 16;

if (curDigit >= 'A' && curDigit <= 'F')
endNum += 10 + (curDigit - 'A');
else
endNum += curDigit - '0';
}
return "" + endNum;
}


public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter the decimal number: ");
String valueIn = keyboard.nextLine ();
String outputOut = hexToDec(valueIn);
System.out.println("The output is: " + outputOut);
}

public static String decimalToBinary(int valueIn) {
int remainder, i = 0;
String binaryNum = "";
while (valueIn != 0) {
remainder = valueIn % 2;
valueIn /= 2;
binaryNum = remainder+binaryNum;
}
return binaryNum;
}

public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Please enter the decimal number: ");
int valueIn = keyboard.nextInt ();
String outputOut = decimalToBinary(valueIn);
System.out.println("The output is: " + outputOut);
}

最佳答案

您可以简单地定义自己的映射并根据注释完全跳过十进制转换路线。

HashMap<char, String> mapping = new HashMap<char, String>();
mapping.put('0', "0000" );
mapping.put('1', "0001" );
mapping.put('2', "0010");
mapping.put('3', "0011");
mapping.put('4', "0100" );
mapping.put('5', "0101");
mapping.put('6', "0110");
mapping.put('7', "0111");
mapping.put('8', "1000");
mapping.put('9', "1001");
mapping.put('a', "1010");
mapping.put('b', "1011");
mapping.put('c', "1100");
mapping.put('d', "1101");
mapping.put('e', "1110");
mapping.put('f', "1111");

然后可以这样做:

String hexValue = "something";
StringBuilder result = new StringBuilder();
for (char c : hexValue) {
// need to do some error checking here.
result.append(mapping[Character.toLowerCase(c)]);
}

System.out.prinltn(result.ToString());

关于java - 十六进制转二进制——java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53183743/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com