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.
//HexToDecimal.java
import java.lang.*;
import java.util.Scanner;
public class HexToDecimal
{
public static void main(String[] args) {
Scanner sc = new
Scanner(System.in);
System.out.print("Enter Hex number
: ");
String hex = sc.nextLine();//Take
input from user
hex = hex.toUpperCase();//To
convert all characters to uppercase
//Direct conversion using built-in
function from Integer Class
int decimal =
Integer.parseInt(hex,16);
System.out.println("conversion
hex-decimal using Integer class : "+hex+" -> "+decimal);
//Building our own method to convert hex to decimal
String numbers =
"0123456789ABCDEF";
int value = 0;
for(int index = 0; index <
hex.length(); index++){
char ch =
hex.charAt(index);
int digit =
numbers.indexOf(ch);
value = 16*value
+ digit;
}
System.out.println("conversion
hex-decimal using our algorithm : "+hex+" -> "+value);
}
}
//OUTPUT
//BINARYTODECIMAL.JAVA
import java.lang.*;
import java.util.Scanner;
public class BinaryToDecimal
{
public static void main(String[] args) {
Scanner sc = new
Scanner(System.in);
System.out.print("Enter Binary
number : ");
String binary =
sc.nextLine();//Take input from user
//Direct conversion using built-in
function from Integer Class
int decimal =
Integer.parseInt(binary,2);
System.out.println("conversion
binary-decimal using Integer class : "+binary+" ->
"+decimal);
//Building our own method to convert binary to decimal
int value = 0,power=0;
for(int index = binary.length()-1;
index >=0 ; index--){
char ch =
binary.charAt(index);
int digit = ch -
'0';//To get 0 or 1
value +=
digit*Math.pow(2,power);
power++;
}
System.out.println("conversion
binary-decimal using our algorithm : "+binary+" ->
"+value);
}
}
//OUTPUT