+ 6

How is this even possible?

public int toDecimal(String bin){ int x=0,dec=0; for(x=0;x<=bin.length()-1;x++){ dec+=(2*((int)bin.charAt(x))); } return dec; } the above code is my binary to decimal converter, however, when I give input 10 it gives output 194, shouldn't it give 2?

25th Mar 2017, 1:55 PM
Prabhakar Dev
Prabhakar Dev - avatar
5 Answers
+ 16
The conversion of char to int gives ASCII value. 49*2 + 48*2 = 194
25th Mar 2017, 2:09 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 14
Sure. Apparently, your conversion logic is not correct. For example, 10110's equivalent decimal is 22, but multiplying each character by 2 will provide 6. The logic should be: 10110 = 1*2^4 + 0*2^3 + 1*2^2 + 1*2^1 + 0*2^0 (^ means power here) = 1*16 + 0*8 + 1*4 + 1*2 + 0*1 = 22 So, here is the corrected code: public static int toDecimal(String bin){ int x=0, y,dec=0; for(x=0, y=bin.length()-1;x<=bin.length()-1;x++, y--){ dec+= (bin.charAt(x)-'0')*Math.pow(2, y); } return dec; } // subtracting ASCII value of '0' will convert the char to int
25th Mar 2017, 2:30 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 6
thanks
25th Mar 2017, 3:30 PM
Prabhakar Dev
Prabhakar Dev - avatar
+ 4
ok
25th Mar 2017, 2:17 PM
Prabhakar Dev
Prabhakar Dev - avatar
+ 4
can you help me here
25th Mar 2017, 2:18 PM
Prabhakar Dev
Prabhakar Dev - avatar