Reputation: 21
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);
Upvotes: 2
Views: 511
Reputation: 25387
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
Upvotes: 3
Reputation: 109623
The digit value was wrong:
int digit = binaryString.charAt(n - 1) - '0';
Upvotes: 2