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);
}
1
  • 2
    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. Commented Aug 9, 2011 at 13:21

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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."
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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.