我对 Java 比较陌生,正在尝试将用户输入转换为十六进制。目前,我尝试先将其转换为字节,但是我收到有关一行的错误 Byte getByte = Byte.parseByte(getCharacter);
整体代码如下所示,
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
Scanner scanner = new Scanner(System.in);
String name = scanner.next();
String binary = "", hexidecimal = "";
ArrayList<Character> chars = new ArrayList<>();
for(char c : name.toCharArray()) chars.add(c);
for(char c : chars) {
try {
String getCharacter = Character.toString(c);
Byte getByte = Byte.parseByte(getCharacter);
String stringByte = Byte.toString(getByte);
binary.concat(stringByte);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
System.out.println(binary);
}
}
我见过answers但是我不明白如何将 char a = '\uffff'
这样的东西合并到我的程序中。
最佳答案
如果您尝试将整个字符串转换为十六进制,最简单的方法是:
public class stringToHex {
public static void main(String[] args) throws UnsupportedEncodingException { //exception is necessary to convert to a byte array
String test = "Hello World";
byte[] bytes = test.getBytes("UTF-8"); //make a byte array out of the string
System.out.println(DatatypeConverter.printHexBinary(bytes)); //use DatetypeConverter to convert binary to hex
}
}
如果您绝对需要接受字符而不是字符串,我认为最简单的解决方案就是转换为字符串,然后转换为字节数组:
byte[] bytes = new String(ch).getBytes("UTF-8");
关于java - 将扫描仪字符转换为字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49032265/