简体   繁体   English

输出错误:二进制到十进制java

[英]Output Error:Binary to decimal java

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. 我的代码的目的是将二进制数(String)n转换为十进制形式。该程序段已成功编译,但输出结果超出了预期。

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);
}
}

This is because s.charAt(i) is a character code of the digit, not its numeric value. 这是因为s.charAt(i)是数字的字符代码 ,而不是数字值。 the UNICODE code point for '0' is U+0030 ; '0'的UNICODE代码点为U+0030 for '1' , it is U+0031 . 对于'1' ,它是U+0031

Change to 改成

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

to fix the problem ( demo on ideone ). 解决该问题( 有关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. 从另一个十进制数字的代码点减去零的代码点会在该代码点和相应的数字之间产生“距离”,该距离对应于该数字的数值。

尝试这个

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

when you put int x=(int)ch; 当你把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 x中保存的值不为1,其对应的unicode值为49,因此要获取for循环中if语句所需的实数
char ch=s.charAt(i); if(ch=='1') x=1 if(ch=='0') x=0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM