0
public class goofy {
    public static void main(String[] args){
        System.out.print(toInt("101"));
    }
    public static int toInt(String Bin){
        int ans = 0;
        for(int i=0;i<Bin.length();i++){
            ans = ans+(int)((int)Bin.charAt(i)*Math.pow(2,Bin.length()-i));
        }
        return ans;
    }
    
}

This is my code, I named it goofy becaus eit acts goofy:) can anyone tell me why this is not working when I try to convert binary(Bin) into decimal?

running the code I expect it to print the decimal integer

Chen Owen
  • 1
  • 1
  • so what number is it printing? – OldProgrammer May 02 '23 at 21:31
  • What does "not working" mean? Please see [ask]. – kaya3 May 02 '23 at 21:31
  • The duplicate question has the best answer, but to address why your code doesn't work: `charAt` gets you a character, and if you convert that to int, you get its utf8 code point value, so you need to subtract `'0'` (character 0, again, as utf8 code) from it to get the real digit value. Then you have an off by one error, you need to use `Bin.length() - i - 1`. The loop body should be (simplified): `ans += (Bin.charAt(i) - '0') * Math.pow(2, Bin.length() - i - 1);`. – Robert May 02 '23 at 21:41

0 Answers0