Java Error Byte.parseByte ()

I have a small error in my code that I cannot for the life I figured out.

I have an array of strings representing binary data (after converting from hex), for example: one index is 1011, the other is 11100. I scan the array and put each index at 0 so that each index is eight bytes. When I try to convert these views to actual bytes, I get an error message when I try to parse the '11111111' The error I get:

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); } 
+6
source share
3 answers

Not a problem here, that byte is a signed type, so its valid values โ€‹โ€‹are -128 ... 127? If you Integer.parseInt() it as an int (using Integer.parseInt() ), it should work.

By the way, you also do not need to enter a number with zeros.

After you parse your binary string into int, you can pass it in bytes, but the value will still be considered signed, so binary 11111111 will become int 255 , and then byte -1 after the translation.

+19
source

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

This way your code will fail because you are too big. The first bit is reserved for positive and negative signs.

according to parseByte

+1
source

byte allows only numbers in the range of -128 to 127. Instead, I would use an int that contains numbers in the range of -2.1 to 2.1 billion.

+1
source

Source: https://habr.com/ru/post/894631/


All Articles