Hexa-Decimal Conversion



Yesterday's laboratory exercise, our professor introduced us to the fascinating world of number systems with a challenging exercise: converting hexadecimal (HEX) numbers to decimal. This task required us to delve into the fundamentals of different number systems and understand how to efficiently translate between them using Java. What seemed like a straightforward conversion quickly revealed its complexity, as we navigated through the intricacies of base-16 to base-10 transformations. This exercise not only sharpened our coding skills but also deepened our understanding of how computers interpret and process different numerical representations. 

Code Explanation

This program converts a hexadecimal number inputted by the user into its decimal equivalent.

1. Imports:

import java.io.*;
java.io.*: This imports the Java input-output classes, which are necessary for reading input from the user.

2. Class Definition

public class HexadecimalToDecimal

A public class named HexadecimalToDecimal is defined. This is the main class for the program.


3. Main Method:

public static void main(String[] args) throws IOException

The main method serves as the entry point of the program. It’s declared with throws IOException to handle any input/output exceptions that may occur during user input.

4. BufferedReader for User Input:

BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

A BufferedReader object bf is created to read input from the console. It wraps InputStreamReader(System.in) to enable efficient reading of characters.

5. Prompt and Read Hexadecimal Input:

System.out.print("Enter the Hexadecimal Number: ");
String str = bf.readLine();

The program prompts the user to enter a hexadecimal number. bf.readLine() reads the input from the console as a string and stores it in str.

6. Convert Hexadecimal to Decimal:

int i = Integer.parseInt(str, 16);

Integer.parseInt(str, 16) converts the string str, which contains the hexadecimal number, into an integer. The second argument 16 specifies that the input is in base 16 (hexadecimal).
The result is stored in the integer variable i.

7. Output the Results:

System.out.println("HexaDecimal : " + str);
System.out.println("Decimal : " + i);

The program prints the original hexadecimal value entered by the user (str).
It then prints the converted decimal value (i).

Sample Execution

In the output shown:

  • The user entered B as the hexadecimal number.
  • B in hexadecimal is equivalent to 11 in decimal.
  • The program correctly displays HexaDecimal : B and Decimal : 11.

Summary

This code takes a hexadecimal number as input from the user, converts it into a decimal number, and prints both the original hexadecimal and the converted decimal value.

Previous Post Next Post

نموذج الاتصال