java.lang.NumberFormatException:值超出范围。值:“8C” 从 String 转换为 byte[] 时基数:16

arj*_*ncc 3 java encoding hex character-encoding

从以下代码中得到以下错误。我想要实现的是将一系列十六进制代码作为字节本身打印到文件中。我该如何修复它,以便我可以在文件中打印 8C

public static void process() {
    System.out.println("File to print");
    String hexString = "418C";
    try {
        byte value[] = getByte(hexString);
        try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
            outputStream.write(value);
        }
    } catch (Exception exp) {
        exp.printStackTrace();
    }
}
    
private static byte[] getByte(String str) {
    byte[] val = new byte[str.length() / 2];
    for (int i = 0; i < val.length; i++) {
        int index = i * 2;
        byte byt = Byte.parseByte(str.substring(index, index + 2), 16);
        val[i] = byt;
    }
    return val;
}
Run Code Online (Sandbox Code Playgroud)

例外

java.lang.NumberFormatException: Value out of range. Value:"8C" Radix:16
    at java.base/java.lang.Byte.parseByte(Byte.java:154)
Run Code Online (Sandbox Code Playgroud)

基于以下链接,我更改为Character.MAX_RADIX,但出现另一个错误。 https://www.tutorialspoint.com/java/lang/byte_parsebyte_radix.htm

以下链接很有帮助 为什么 Byte.parseByte("80", 16) 失败?

vbe*_*nar 5

Byte.parseByte(str, 16)需要签名输入。Byte.parseByte("-1", 16)例如,您可以编写,因为-1适合 Javabyte类型,但不能编写Byte.parseByte("80", 16),因为128不适合 Javabyte类型。

您可以替换Byte.parseByte(str.substring(index, index + 2), 16)(byte) Integer.parseInt(str.substring(index, index + 2), 16),它会正常工作。

java.util.HexFormat.of().parseHex(hexString)如果您使用的是 Java 17,则可以使用getByte(hexString).