Alex Rivera | Logout

Java Byte.parseByte() error

Asked 2011-08-09T13:13:05.377
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);
}
Edit
Report

2 Answers

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

answered 2011-08-09T13:19:17.660
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.

answered 2011-08-09T13:23:16.293

Your Answer