Java Byte.parseByte() 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6996707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:11:49  来源:igfitidea点击:

Java Byte.parseByte() error

javaparsingbytenumberformatexception

提问by Josh

I'm having a small error in my code that I can not for the life of me figure out.

我的代码中有一个小错误,我一生都无法弄清楚。

I have an array of strings that are representations of binary data (after converting them from hex) for example: one index is 1011 and another is 11100. I go through the array and pad each index with 0's so that each index is eight bytes. When I try to convert these representations into actual bytes I get an error when I try to parse '11111111' The error I get is:

我有一个表示二进制数据的字符串数组(在将它们从十六进制转换之后),例如:一个索引是 1011,另一个是 11100。我遍历数组并用 0 填充每个索引,以便每个索引是 8 个字节。当我尝试将这些表示形式转换为实际字节时,当我尝试解析 '11111111' 时出现错误我得到的错误是:

java.lang.NumberFormatException: Value out of range. Value:"11111111" Radix:2

Here is a snippet:

这是一个片段:

String source = a.get("image block");
int val;
byte imageData[] = new byte[source.length()/2];

try {
    f.createNewFile();
    FileOutputStream output = new FileOutputStream(f);
    for (int i=0; i<source.length(); i+=2) {
        val = Integer.parseInt(source.substring(i, i+2), 16);
        String temp = Integer.toBinaryString(val);
        while (temp.length() != 8) {
            temp = "0" + temp;
        }
    imageData[i/2] = Byte.parseByte(temp, 2);
}

回答by biziclop

Isn't the problem here that byteis a signed type, therefore its valid values are -128...127? If you parse it as an int(Using Integer.parseInt()), it should work.

这里的问题不是byte有符号类型,因此其有效值为 -128...127?如果您将其解析为int(Using Integer.parseInt()),它应该可以工作。

By the way, you don't have to pad the number with zeroes either.

顺便说一句,您也不必用零填充数字。

Once you parsed your binary string into an int, you can cast it to a byte, but the value will still be treated as signed, so binary 11111111will become int 255first, then byte -1after the cast.

将二进制字符串解析为 int 后,您可以将其转换为字节,但该值仍将被视为有符号,因此binary 11111111将成为int 255第一个,然后byte -1在转换之后。

回答by Chris Aldrich

Well, eight one's is 255, and according to java.lang.Byte, the MAX_VALUE is 2^7 - 1 or positive 127.

好吧,8 个是 255,根据 java.lang.Byte,MAX_VALUE 是 2^7 - 1 或正 127。

So your code will fail because you number is too large. The first bit is reserved for the positive and negative sign.

所以你的代码会失败,因为你的数字太大了。第一位是为正负号保留的。

according to parseByte

根据parseByte

回答by fireshadow52

byte's only allow numbers in the range of -128 to 127. I would use an intinstead, which holds numbers in the range of -2.1 billion to 2.1 billion.

byte只允许 -128 到 127 范围内的数字。我会使用 anint代替,它保存 -21 亿到 21 亿范围内的数字。