Java Byte.parseByte() error
Asked Answered
M

3

9

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:

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);
}
Misprize answered 9/8, 2011 at 13:13 Comment(1)
byte's only allow numbers in the range of -128 to 127. I would use an int instead, which holds numbers in the range of -2.1 billion to 2.1 billion.Mounting
U
28

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

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 11111111 will become int 255 first, then byte -1 after the cast.

Ultimately answered 9/8, 2011 at 13:15 Comment(1)
In Byte.parseByte(String s, int radix) throws..., s is assumed as positive unless it has an explicit sign ('+'/'-') as the first character. According its link documentation: "The characters in the string must all be digits, of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value) except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value."Denning
N
1

Well, eight one's is 255, and according to java.lang.Byte, the MAX_VALUE is 2^7 - 1 or positive 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

Nealy answered 9/8, 2011 at 13:19 Comment(0)
M
1

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

Mounting answered 9/8, 2011 at 13:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.