Frage

The aim of my code was to convert binary numbers(String)n to decimal form This program segment compiled succesfully but the output is coming way bigger than expected.

Need some help.Thanks in advance

public class bindecstr {
public static void main(String args[]){
    String s="11111";
    int l=s.length();
    double sum=0;
    int t=l-1;
for(int i=0;i<l;i++){   
    char ch=s.charAt(i);
    int x=(int)ch;
    double d=(Math.pow(2,t-i))*x;
    sum=sum+d;
}
System.out.println(sum);
}
}
War es hilfreich?

Lösung

This is because s.charAt(i) is a character code of the digit, not its numeric value. the UNICODE code point for '0' is U+0030; for '1', it is U+0031.

Change to

int ch=s.charAt(i) - '0';

to fix the problem (demo on ideone). The reason this works is that the code points of digits are arranged sequentially. Subtracting the code point of zero from a code point of another decimal digit produces "the distance" between that code point and the corresponding digit, which corresponds to the numeric value of the digit.

Andere Tipps

try this

int x = (int) ch - '0';

when you put int x=(int)ch; the value that saved in x is not 1 its the corresponding unicode value that is 49 so to take the real value of one you gonna need if statement in the for loop
char ch=s.charAt(i); if(ch=='1') x=1 if(ch=='0') x=0

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top