Write a program that user enters 4 position hexadecimal number and you output th
ID: 3602954 • Letter: W
Question
Write a program that user enters 4 position hexadecimal number and you output the decimal value along with hexadecimal value. Thus 4A7C would output “Hexadecimal-4A70 equals decimal 19068". You can NOT use any commands to convert text to numbers. Pseudocode: input 4 digit hexadecimal number as string get each character at each position and calculate decimal number 4 A 7 C 4 16310 162 7*161 12 160 4 charAt(O) 10- charAt(1) 7 charAt(2) 12-charAt(3) HINT: Math.pow(16,indexK) is the same as 16indexk see example above. output input string as well as decimal value EXTRA CREDIT-MAKE PROGRAM READ IN HEXADECIMAL NUMBER ANY LENGTHExplanation / Answer
HexDec.java
import java.util.Scanner;
public class HexDec {
public static void main(String[] args) {
//Creating Scanner Object for reading input string
Scanner s = new Scanner(System.in);
System.out.println("Enter the Hexadecimal number:");
//Reading String using scanner object
String hex = s.next();
//Converting String into upper case
hex = hex.toUpperCase();
//Initializing
int w=0,p=0;
char letter;
long decimal = 0L;
//Digits of a decimal value from 0 to F
String str = "0123456789ABCDEF";
//Iterate the loop from last character to 0th character
// of input String hex
for(int k=hex.length()-1;k>=0;k--){
//Get each character from input string hex
letter = hex.charAt(k);
//Find the index of character in string str
w = str.lastIndexOf(letter);
//Calculate the value for powers of 16
//in each iteration
decimal = decimal + w*(long)Math.pow(16, p);
p++;
}
//Printing the Decimal value for Given Hexadecimal
System.out.println("Hexa Decimal = "+hex+" equals decimal = "+decimal);
s.close();
}
}
Output:
Enter the Hexadecimal number:
4a7c
Hexa Decimal = 4A7C equals decimal = 19068
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.