Java Byte.parseByte() error

2019-06-18 03:37发布

问题:

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:

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.



回答2:

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



回答3:

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.