gpt4 book ai didi

java - 将十六进制字符串转换为字节中的二进制字符串会抛出 NumberFormatException

转载 作者:行者123 更新时间:2023-11-30 04:10:40 24 4
gpt4 key购买 nike

public static byte[][] keyArray = new byte[4][4]; 
String hex = "93";
String hexInBinary = Integer.toBinaryString(Integer.parseInt(hex, 16));
keyArray[row][col] = Byte.parseByte(hexInBinary,2); //this line causes the error

这是我收到的错误消息,

"Exception in thread "main" java.lang.NumberFormatException: Value out of range. Value:"10010011" Radix:2."

我不想使用 getBytes(),因为我实际上有一个很长的字符串,“0A935D11496532BC1004865ABDCA42950”。我想一次读取 2 个十六进制并转换为字节。

编辑:

我是如何解决这个问题的:

String hexInBinary = String.format("%8s", Integer.toBinaryString(Integer.parseInt(hex, 16))).replace(' ', '0');
keyArray[row][col] = (byte)Integer.parseInt(hexInBinary, 2);

最佳答案

正如异常消息中所写,您尝试转换为字节的字符串超出了最大值。一个字节可以有的值。

在您的示例中,字符串“10010011”等于 147,但字节变量的最大值为 2^7 - 1 = 127。

您可能需要查看字节类文档; http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Byte.html#MAX_VALUE

所以我建议使用Integer.parseInt(),而不是parseByte方法,然后将int值转换为byte值,当你将其转换为byte值时,整数值147将变成-109。

关于java - 将十六进制字符串转换为字节中的二进制字符串会抛出 NumberFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19671594/

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