Respuesta :
Answer:
I am writing a JAVA program. Let me know if you want the program in some other programming language.
import java.util.Scanner; //to take input from user
public class HexaToBinary{ //class to convert hexa to binary number
public static void main(String[] args) {// start of main() function body
//creates instance of Scanner class
Scanner input = new Scanner(System.in);
//prompts user to enter a hexadecimal number
System.out.print("Enter a hex digit: ");
char hexadecimal = input.nextLine().charAt(0);//reads input from user
String binary = ""; //variable to hold corresponding binary number
/*switch statement is used to convert hexadecimal input to corresponding binary number. the switch statement has cases. Each case has a hexa decimal number. The user's input is stored in hexadecimal variable which is given as a choice parameter to switch statement. If the input matches any of the cases in switch statement, the body of that case is executed which prints the corresponding binary number otherwise invalid input message is displayed in output */
switch (hexadecimal) {
case '0': binary = "0"; break;
case '1': binary = "1"; break;
case '2': binary = "10"; break;
case '3': binary = "11"; break;
case '4': binary = "100"; break;
case '5': binary = "101"; break;
case '6': binary = "110"; break;
case '7': binary = "111"; break;
case '8': binary = "1000"; break;
case '9': binary = "1001"; break;
//here both the upper and lower case letters are defined in case, so the user //can enter a hexadecimal in lowercase or uppercase
case 'a':
case 'A': binary = "1010"; break;
case 'b':
case 'B':binary = "1011"; break;
case 'c':
case 'C': binary = "1100"; break;
case 'd':
case 'D': binary = "1101"; break;
case 'e':
case 'E': binary = "1110"; break;
case 'f':
case 'F': binary = "1111"; break;
default: System.out.println(hexadecimal + " is invalid input"); System.exit(1); } //displays this message if user enters invalid input e.g T
System.out.println("The binary value is " + binary); } }
//prints the corresponding binary number of the hexadecimal input
Explanation:
The program is well explained in the comments mentioned with each line of the program. Lets take an example of user input.
For example if user enters b in input then the cases of the switch statement are searched for by the program to select the corresponding binary number of the input hexadecimal. So b is present in case 'b': case 'B':binary = "1011"; break; So the value of binary is 1011 and this value is displayed on the screen with this statement System.out.println("The binary value is " + binary); So the output is: The binary value is 1011
The screenshot of output and program are attached.
