I am trying to parse the following String to Byte.But it gives me NumberFormat Exception.Can some body tell me what is the solution for this?
Byte.parseByte("11111111111111111111111110000001", 2);
I am trying to parse the following String to Byte.But it gives me NumberFormat Exception.Can some body tell me what is the solution for this?
Byte.parseByte("11111111111111111111111110000001", 2);
Out of range of byte ie -128 to 127. From parseByte(String s,int radix) javadoc:
public static byte parseByte(String s, int radix)throws NumberFormatException
Parses the string argument as a signed byte in the radix specified by the second argument. 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. The resulting byte value is returned. An exception of type NumberFormatException is thrown if any of the following situations occurs:
- The first argument is null or is a string of length zero.
- The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
- Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') provided that the string is longer than length 1.
- The value represented by the string is not a value of type byte.
Returns: the byte value represented by the string argument in the specified radix Throws: NumberFormatException - If the string does not contain a parsable byte.
Byte.parseByte()
handles binary string as sign-magnitude not as a 2's complement, so the longest length you can have for a byte is 7 bits with a sign.
In other words, to represent -127
, you should use:
Byte.parseByte("-111111", 2);
The following throws NumberFormatException
:
Byte.parseByte("10000000", 2);
However, the binary literal of -127 is:
byte b = (byte) 0b10000000;
The same behavior is applied to the other parseXXX()
methods.
from javadocs
An exception of type NumberFormatException is thrown if any of the following situations occurs:
- The first argument is null or is a string of length zero.
- The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
- Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') provided that the string is longer than length 1.
- The value represented by the string is not a value of type byte.
Your value is the second case that is out of range -128 to 127
Value is too large to be parsed in byte Try this:
new BigInteger("011111111111111111111111110000001", 2).longValue();