In: Computer Science
(1) Covert a Hexadecimal to decimal (there is a video for you to watch too). Then write a program that can convert a binary to decimal (only for integer case).
a) Directly use Java built-in method to do this. In this case, only couple lines of code. Hint: Study Integer class in Java.
b) Write your own code to convert a binary to decimal from scratch. The input is a binary string. The program output is its corresponding decimal value. This way you need to design the algorithm.
Solution (a) : Binary to Decimal Using In built Java method:
Code:
public class BinToDec {
public static void main(String args []) {
String binary="1010";
int decimal = Integer.parseInt(binary,2);
System.out.println(decimal);
}
}
Output:
Solution (b) : Binary to Decimal without in-built method:
Code:
public class BinToDec {
public static void main(String args []) {String
binary="1100";
int binaryNum = Integer.parseInt(binary);
int dec = 0;
int p = 0;
while(true){
if(binaryNum == 0){
break;
} else {
int temp = binaryNum%10;
dec += temp*Math.pow(2, p);
binaryNum = binaryNum/10;
p++;
}
}
System.out.println(dec);
}
}
Output: