In: Computer Science
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).
There are two ways to do so.
Easy way: Directly use Java built-in method to do this. In this case, only couple lines of code. Hint: Study Integer class in Java.
Hard way: 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.
Student need to do both ways and test them correctly to get 100% credit. If student only did one way or another, the maximum grade is 80%.
SYSTEM OF HEXADECIMAL :
Hexadecimal | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
Decimal | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
Conversion of Hexadecimal to Decimal :
Let the hexadecimal need to be converted be (abc)16 .
Now, moving from right to left increase the power of 16 starting from 0 and multiple with the encountering digits, and each multiples to generate the corresponding decimal number.
For eg.: E7A916 = 14×163+7×162+10×161+9×160= 57344+1792+160+9 =(59305)10
Program to convert binary to decimal:
Easy Way:
import java.util.*;
class easyway
{
public static void main(String args[])
{
Scanner a=new Scanner(System.in);
String s=a.nextLine(); //input line for the binary
string
System.out.println("Required decimal number is:");
System.out.println(Integer.parseInt(s,2)); //conversion
and printing of required decimal number using built
in
// function, Integer.parseInt
}
}
Hard way:
import java.util.*;
class Hardway
{
public static void main(String args[])
{
Scanner a=new Scanner(System.in);
int n=a.nextInt(); //input line
int d=0,p=0; // variable declaration for the
calculation of decimal number
while(n!=0) // loop until the complete binary digits
are exhausted
{
d+=((n%10)*Math.pow(2,p));
n=n/10;
p++;
}
System.out.println("Required Decimal number is:");
System.out.println(d);
}
}