Binary to Denary Converter in Java

佐手、 提交于 2019-12-11 03:23:39

问题


trying to make a converter of binary to denary in java, but I'm not sure whats going wrong, I have a feeling its in my loop, any help would be much appreciated! I am following pseudo code if you would like to see it!

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

回答1:


The absolute easiest way is with Integer.parseInt(String, 2); (in your case: Integer.parseInt(binaryString, 2);).

However, if you really want to run the loop:

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

Personally, I'd do this if I really wanted to reinvent the wheel:

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



回答2:


The digit value was wrong:

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


来源:https://stackoverflow.com/questions/21416637/binary-to-denary-converter-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!