Java中的二进制到Denary转换器

时间:2014-01-28 20:55:49

标签: java binary converter

试图在java中制作一个二进制转换器来判断,但我不确定是什么问题,我感觉它在我的循环中,任何帮助都会非常感激!如果你想看到它,我正在关注伪代码!

System.out.println("Enter a binary number");

Scanner sc = new Scanner(System.in);
String binaryString = sc.next();

int binaryLength = binaryString.length();

int multiplier = 1;
int denaryValue = 0; 

for(int n = binaryLength; n >= 1; n--){
    int digit = n;
    denaryValue = denaryValue + digit * multiplier;
    multiplier = multiplier * 2;
}
System.out.println("The denary equivalent is " + denaryValue);

2 个答案:

答案 0 :(得分:3)

绝对最简单的方法是Integer.parseInt(String, 2);(在您的情况下:Integer.parseInt(binaryString, 2);)。

但是,如果你真的想要运行循环:

for(int n = binaryLength; n >= 1; n--){
    int digit = binaryString.charAt(n - 1) - '0';
    denaryValue = denaryValue + digit * multiplier;
    multiplier = multiplier * 2;
}

就个人而言,如果我真的想重新发明轮子,我会这样做:

if (!binaryString.matches("[01]+")) {
    //here we know that there is a character that is not a 0 or a 1
    //or that the string is empty
}
for(char c : binaryString.toCharArray()) {
    denaryValue += c - '0';
    denaryValue <<= 1; //binary left shift; multiply by 2
}
denaryValue >>= 1; //binary right shift; divide by 2

答案 1 :(得分:2)

数字值错误:

int digit = binaryString.charAt(n - 1) - '0';