I have to write a method that changes binary to decimal. Write a method that will convert the supplied binary digit (as a string) to a decimal number.
- convertToDecimal("01101011") = 107
- convertToDecimal("00001011") = 11
i have created it to change decimal to binary however im not sure how to create it binary to decimal.
public String convertToBinary(int decimal) {
int n = decimal;
int digit;
String out = "";
while (n > 0){
n = decimal/2;
digit = decimal % 2;
out = digit + out;
decimal = n;
}
out = addPadding(out);
return out;
}
private String addPadding(String s){
String out = s;
int len = s.length();
if (len == 8) return s;
else{
switch(len){
case 7:
out = "0"+s;
break;
case 6:
out = "00"+s;
break;
case 5:
out = "000"+s;
break;
}
}
return out;
}
}
intis not a decimal number. It just gets displayed in decimal format by default when you print it. You can also print it in binary, octal and hexadecimal formats. Intrinsically, an int is neither decimal nor hex. Its appearance is only what you choose to print it as.