I am working at converting string number into binary. But Eclipse throws a NumberFormatException. Can I ask you, to look at my code? I have no idea what is wrong..
public float liczbaF(String lancuch){
float array [] = new float [31];
float liczba;
double mantysa;
int znak;
long cecha;
char element[] = new char[22];
String temp="";
if (lancuch.charAt(0)=='1')
znak=-1;
else
znak=1;
for(int i=1;i<8;i++)
{
element[i-1] = lancuch.charAt(i);
}
temp=String.valueOf(element);
System.out.println(temp);
cecha=Integer.parseInt(temp,10);
cecha=cecha-127;
System.out.println(cecha);
for(int i=31;i>9;i--)
{
element[31-i] = lancuch.charAt(i);
}
temp=String.valueOf(element);
mantysa=(((Integer.parseInt(temp,10))/(pow(2,22)))+1);
liczba=(float)(mantysa*pow(2,cecha));
return liczba;
}
It throws:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1001101
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Konwersja.liczbaF(Konwersja.java:30)
at Main.main(Main.java:10)
I will be grateful for any help. Thank you
Your element array is 22 long:
but you only fill in the first 7 elements:
So there are null characters at the end of the string, which make it unparseable as an integer. This works better:
I would recommend using a StringBuilder to add characters to a String, not a char array.