I am learning bit manipulation in java. So,I am converting binary string to integers bytes and short. Here is my program :-
byte sByte,lByte; // 8 bit
short sShort,lShort; // 16 bit
int sInt,lInt; // 32 bit
sByte= (byte)(int)Integer.valueOf("10000000", 2); //Smallest Byte
lByte= (byte) ~sByte;
sShort= (short)(int)Integer.valueOf("1000000000000000", 2); //Smallest Short
lShort = (short) ~sShort;
sInt = (int) (int)Integer.valueOf("10000000000000000000000000000000", 2); //Smallest Int
lInt= (int)~sInt;
System.out.println("\"10000000\" \"8 bit\" byte=>"+sByte+"\t~byte=>"+lByte);
System.out.println("\"1000000000000000\" \"16 bit\" short=>"+sShort+"\t~short=>"+lShort);
System.out.println("\"10000000000000000000000000000000\" \"32 bit\" int=>"+sInt+"\t~int=>"+lInt);
Byte and Short are being converting and giving smallest Byte and smallest Short Value while Integer is not getting converted.
It is throwing NumberFormatException which is as follows :-
Exception in thread "main" java.lang.NumberFormatException: For input string: "10000000000000000000000000000000"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:583)
at java.lang.Integer.valueOf(Integer.java:740)
at com.learnjava.BitsManipulation.start(BitsManipulation.java:14)
at com.learnjava.learnjava.main(learnjava.java:9)
and if i comment those 3 integer converting lines :-
// sInt = (int) (int)Integer.valueOf("10000000000000000000000000000000", 2); //Smallest Int
// lInt= (int)~sInt;
// System.out.println("\"10000000000000000000000000000000\" \"32 bit\" int=>"+sInt+"\t~int=>"+lInt);
It is giving me output :-
"10000000" "8 bit" byte=>-128 ~byte=>127
"1000000000000000" "16 bit" short=>-32768 ~short=>32767
which is fine.I have checked length of string twice which is of 32 length and integer is of 32 bit in java in this way it should work while that is not case here.
If i remove one 0 or 1 from 32 length string or replace 1 to 0 then it also works which is as follow :-
sInt = (int) (int)Integer.valueOf("00000000000000000000000000000000", 2); //Smallest Int
lInt= (int)~sInt;
System.out.println("\"00000000000000000000000000000000\" \"32 bit\" int=>"+sInt+"\t~int=>"+lInt);
sInt = (int) (int)Integer.valueOf("1000000000000000000000000000000", 2); //Smallest Int
lInt= (int)~sInt;
System.out.println("\"1000000000000000000000000000000\" \"31 bit\" int=>"+sInt+"\t~int=>"+lInt);
output is as follows:-
"00000000000000000000000000000000" "32 bit" int=>0 ~int=>-1
"1000000000000000000000000000000" "31 bit" int=>1073741824 ~int=>-1073741825
i am getting confused on this. Please tell me reason why it is throwing NumberFormatException and solution for this problem.
BigInteger