The aim of this method is to convert the supplied binary digit (as a string) to a decimal number, but I am not getting the result the question wants with the code I have for example convertToDecimal("01101011") = 107
, and I'm am unsure I believe im converting the binary to decimal number right. for example:
Test
System.out.println(convertToDecimal("11001101")); = 205
ive tried a while loop and creating ints but it's just not giving me the same results
public static int binaryToDecimal(String binary) {
int decimal = 0;
int power = 0;
int currentIndex = binary.length() - 1;
while (currentIndex>=0) {
int currentDigit = binary.charAt(currentIndex) - '0';
decimal += currentDigit * Math.pow(2, power);
power++;
currentIndex--;
}
return decimal;
}
I expected to the output to be:
convertToDecimal("01101011") = 107
convertToDecimal("00001011") = 11 ,
System.out.println(convertToDecimal("11001101")); = 205
but none were right
I ran your code, and it worked. But I need to make one simple change:
System.out.println(convertToDecimal("11001101")); = 205
must be changed to:
System.out.println(binaryToDecimal("11001101")); = 205
because binaryToDecimal() is the actual name of your function:
public static int binaryToDecimal(String binary) {
int decimal = 0;
int power = 0;
int currentIndex = binary.length() - 1;
while (currentIndex>=0) {
int currentDigit = binary.charAt(currentIndex) - '0';
decimal += currentDigit * Math.pow(2, power);
power++;
currentIndex--;
}
return decimal;
}
After that, it all works fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.