How To Convert Hexadecimal To Decimal In Java

The number systems hexadecimal and decimal are widely used in computer programming. The decimal value uses a base-10 system, hexadecimal is a base-16 system that is frequently used to represent binary values more concisely.

The hexadecimal values are frequently encountered as strings in Java; they may need to be converted to decimal format for certain calculations or operations.

The conversion of each hexadecimal digit to its decimal value including addition of values together that yields the final decimal value.

Why Converting Hexadecimal To Decimal In Java in required

The conversion from Hexadecimal to Decimal in Java has significance as follows:

  • Binary value representation: This is important for representation of the binary value that is considered as more readable and compact.
  • Easier to implement: Converting hexadecimal to decimal makes binary values easier to manipulate and analyze.
  • Input validation: Hexadecimal values may be entered by users or read from external sources in some cases. Converting these values to decimal makes validation and error checking easier.
  • Arithmetic operations: Some arithmetic operations, such as addition and multiplication, may require decimal values. These operations can be done easily with accurate results.
  • Database operations: Hexadecimal values can be stored as binary data in database systems. Converting these values to decimal allows for more efficient data retrieval and manipulation.
  • Debugging: Converting hexadecimal values to decimal can aid in debugging code or identifying problems with data representation.
  • Network Communication: Hexadecimal values can be used in network communication protocols. Converting these values to decimal makes network data easier to interpret and analyze.

Methods for Converting Hexadecimal To Decimal In Java

In Java, you can find these three method for converting Hexadecimal to Decimal:

  1. Using Integer.parseInt() method
  2. Using the Math.pow() method
  3. Using the bitwise operators

Now, let’s explore each method with detailed explanation of codes for better understanding:

Approach 1: Using Integer.parseInt() method for Converting Hexadecimal To Decimal In Java

The parseInt() method is implemented that can help in converting Hexadecimal to Decimal value in Java.

Sample Code:

public class HexToDecimal {
    public static void main(String[] args) {
        String hexString = "1A"; // hexadecimal string
        int decimalValue = Integer.parseInt(hexString, 16); // convert to decimal integer using parseInt() method
        System.out.println("Hexadecimal value: " + hexString); // output the hexadecimal string
        System.out.println("Decimal value: " + decimalValue); // output the decimal integer
    }
}

Output:

Hexadecimal value: 1A
Decimal value: 26

Explanation of code:

  • Declare a class named HexToDecimal.
  • Declare the main() method.
  • Declare a hexadecimal string variable hexString with the value “1A”.
  • Implementation of Integer.parseInt() method.
  • The method’s second parameter is the radix, which has the value 16.
  • Store the decimal integer value in a variable named decimalValue.
  • The output is displayed with System.out.println() method.

Approach 2: Using the Math.pow() method for Converting Hexadecimal To Decimal In Java.

It includes iterating over each digit in the hexadecimal string that can help in converting it to decimal, then it is multiplied with a power of 16. The values obtained are then added together to obtain the decimal equivalent.

Sample Code:

public class HexToDecimal {
    public static void main(String[] args) {
        String hexString = "1A"; // hexadecimal string
        int decimalValue = 0;
        for (int i = 0; i < hexString.length(); i++) {
            char c = hexString.charAt(i);
            int digit = Character.digit(c, 16); // convert the character to its integer value
            int power = hexString.length() - 1 - i;
            decimalValue += digit * Math.pow(16, power); // multiply the digit by its corresponding power of 16 and add to the decimal value
        }
        System.out.println("Hexadecimal value: " + hexString); // output the hexadecimal string
        System.out.println("Decimal value: " + decimalValue); // output the decimal integer
    }
}

Output:

Hexadecimal value: 1A
Decimal value: 26

Explanation of code:

  • Create a class called HexToDecimal.
  • Declare the main() function.
  • Declare hexString as a hexadecimal string variable with the value “1A.”
  • Declare an integer variable decimalValue and initialize it to 0.
  • Use a for loop to iterate over each character in the hexString.
  • For each character, convert it to its integer value using the Character.digit() method with a radix of 16.
  • Calculate the corresponding power of 16 for the current digit using the length of the hexString and the current index.
  • Multiply the digit by its corresponding power of 16 and add it to the decimalValue.
  • Get the output with System.out.println() method.

Approach 3: Using the bitwise operators for Converting Hexadecimal To Decimal In Java

In this method, the hexadecimal string is converted to a binary string, and the binary string is then converted to a decimal integer.

Sample Code:

public class HexToDecimal {
    public static void main(String[] args) {
        String hexString = "1A"; // hexadecimal string
        int decimalValue = 0;
        for (int i = 0; i < hexString.length(); i++) {
            char c = hexString.charAt(i);
            int digit = Character.digit(c, 16); // convert the character to its integer value
            decimalValue = (decimalValue << 4) | digit; // shift the decimal value left by 4 bits and bitwise OR with the current digit
        }
        System.out.println("Hexadecimal value: " + hexString); // output the hexadecimal string
        System.out.println("Decimal value: " + decimalValue); // output the decimal integer
    }
}

Output:

Hexadecimal value: 1A
Decimal value: 26

Explanation of code:

  • Create a class called HexToDecimal.
  • Declare the main() function.
  • Declare hexString as a hexadecimal string variable with the value “1A.”
  • Declare and initialize the integer variable decimalValue to 0.
  • To iterate over each character in the hexString, use a for loop.
  • Use the Character.digit() method with a radix of 16 to convert each character to its integer value.
  • Shift the decimalValue left by 4 bits using the bitwise left shift operator (<<).
  • Bitwise OR the shifted decimalValue with the current digit using the bitwise OR operator (|).
  • Store the result back into decimalValue.
  • Output the hexadecimal string to the console using the System.out.println() method.
  • Output the decimal integer to the console using the System.out.println() method.

Best Approach for Converting Hexadecimal To Decimal In Java

After the analyzing and comparing all methods for converting Hexadecimal To Decimal, we can say Integer.parseInt() method is the best approach for conversion because of following reasons:

  • Simplicity: The Integer.parseInt() method is a built-in Java method that is very simple to use. Simply passing the hexadecimal string to the method yields the decimal integer value.
  • Efficiency: The Integer.parseInt() method is a highly optimized method that uses bitwise operations and other techniques to quickly and efficiently convert hexadecimal to decimal.
  • Error Handling: The Integer.parseInt() method includes error handling. The method will throw a NumberFormatException if the input string is not a valid hexadecimal string.
  • Flexibility: The Integer.parseInt() method is versatile in that it can handle both uppercase and lowercase hexadecimal strings, as well as negative hexadecimal numbers.
  • Standardization: The Integer.parseInt() method in Java is a standardized method for converting hexadecimal to decimal. This means that it is widely used and recognised by other programmers, which can make your code more readable and maintainable.

Sample Problems for Converting Hexadecimal To Decimal In Java

Sample Problem 1

Write a Java program that reads a file containing a list of hexadecimal strings, one per line, and converts each string to its decimal equivalent. The program should then write the decimal values to a new file, one per line. If a line in the input file contains an invalid hexadecimal string, the program should skip that line and write a message to the output file indicating that the input was invalid.

Solution:

  • The code defines a class called HexToDecimalConverter with a main method that takes no arguments.
  • The code defines two string variables inputFilename and outputFilename which are used to specify the input and output file names respectively.
  • The code uses a try-with-resources statement to create a BufferedReader and a FileWriter object to read from the input file and write to the output file respectively.
  • The code then enters a loop to read each line from the input file using the readLine() method of the BufferedReader object.
  • For each line read from the input file, the code trims any leading or trailing whitespace using the trim() method.
  • The code then checks if the input is a valid hexadecimal string by iterating over each character in the line and checking if it’s a digit (0-9) or a letter (A-F or a-f). If the input is invalid, the code sets a boolean flag validInput to false.
  • If the input is valid, the code uses the Integer.parseInt() method with a radix of 16 to convert the hexadecimal string to an integer.
  • The code then writes the decimal integer to the output file using the write() method of the FileWriter object.
  • If the input is invalid, the code writes a message to the output file indicating that the input was invalid.
  • The catch block catches any IOException that may occur while reading from or writing to the files and prints the stack trace.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class HexToDecimalConverter {
    public static void main(String[] args) {
        String inputFilename = "input.txt";
        String outputFilename = "output.txt";

        try (BufferedReader reader = new BufferedReader(new FileReader(inputFilename));
             FileWriter writer = new FileWriter(outputFilename)) {
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();

                // Check if the input is a valid hexadecimal string
                boolean validInput = true;
                for (int i = 0; i < line.length(); i++) {
                    char c = line.charAt(i);
                    if (!Character.isDigit(c) && (c < 'A' || c > 'F') && (c < 'a' || c > 'f')) {
                        validInput = false;
                        break;
                    }
                }

                if (validInput) {
                    int decimalInt = Integer.parseInt(line, 16);
                    writer.write(decimalInt + "\n");
                } else {
                    writer.write("Invalid input: " + line + "\n");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

Input:
12
34
AB
ZC
Output:
18
52
171
Invalid input: ZC

Sample Problem 2

Convert a Hexadecimal number N to an equivalent decimal number, i.e. convert a number with base value 16 to a number with base value 10. To represent any numeric value, the decimal number system uses 10 digits 0-9, while the Hexadecimal number system uses 0-9, A-F.

Solution:

  • We start by creating a Scanner object to read input from the user.
  • We prompt the user to enter a hexadecimal number and read it in as a string using the nextLine() method. We convert the input to uppercase to simplify our processing later on.
  • We initialize two variables, decimalNumber and power, to 0. We will use these variables to keep track of the decimal equivalent of the hexadecimal number and the current power of 16 that we are using.
  • We loop through the characters of the input string from right to left, since the least significant digit of a hexadecimal number is on the right.
  • For each character, we check whether it is a valid hexadecimal digit. If it is, we convert it to an integer value using the appropriate formula. If it is not a valid digit, we print an error message and exit the program.
  • We then use the Math.pow() method to compute the decimal value of the current digit and add it to our running total. We also increment the power variable to account for the next digit’s place value.
  • Once we have processed all the digits, we print out the decimal equivalent of the original hexadecimal number.
import java.util.Scanner;

public class HexToDecimalConverter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a hexadecimal number: ");
        String hexNumber = scanner.nextLine().toUpperCase(); // Convert input to uppercase

        int decimalNumber = 0;
        int power = 0;

        for (int i = hexNumber.length() - 1; i >= 0; i--) {
            char hexChar = hexNumber.charAt(i);
            int hexDigit;
            if (hexChar >= '0' && hexChar <= '9') {
                hexDigit = hexChar - '0';
            } else if (hexChar >= 'A' && hexChar <= 'F') {
                hexDigit = hexChar - 'A' + 10;
            } else {
                System.out.println("Invalid input: " + hexNumber);
                return;
            }
            decimalNumber += hexDigit * Math.pow(16, power);
            power++;
        }

        System.out.println("The decimal equivalent of " + hexNumber + " is " + decimalNumber);
    }
}

Output:

Enter a hexadecimal string: ABC
The decimal equivalent of ABC is 2748

Sample Problem 3

Create a Java program that requests that the user enter a hexadecimal number as a string.  Remove any leading or trailing whitespace and convert the string to uppercase.  Using bitwise operators, loop through the string’s characters and convert each hexadecimal digit to its decimal equivalent. Multiply each digit’s decimal value by the appropriate power of 16 and add the results to get the final decimal value. Show the user the final decimal value.

Solution:

  • We start by prompting the user to enter a hexadecimal number as a string and reading the input using the Scanner class.
  • We then convert the string to uppercase and remove any leading or trailing whitespace using the trim() and toUpperCase() methods.
  • We loop through each character of the string and convert each hexadecimal digit to its decimal equivalent using bitwise operators. We do this by checking if the character is a digit or a letter, and using the appropriate conversion formula based on the value of the character.
  • We then multiply the decimal value of each digit by the appropriate power of 16 and add the results together to obtain the final decimal value. We do this by using a loop and bitwise operators to extract the least significant digit of the decimal value at each iteration.
  • Finally, we display the final decimal value to the user using the System.out.println() method.
import java.util.Scanner;

public class HexToDecimalConverter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter a hexadecimal number as a string.
        System.out.print("Enter a hexadecimal number: ");
        String hexString = scanner.nextLine();

        // Convert the string to uppercase and remove any leading or trailing whitespace.
        hexString = hexString.trim().toUpperCase();

        // Loop through the characters of the string and convert each hexadecimal digit to its decimal equivalent using bitwise operators.
        int decimalValue = 0;
        for (int i = 0; i < hexString.length(); i++) {
            char hexChar = hexString.charAt(i);
            if (hexChar >= '0' && hexChar <= '9') {
                decimalValue = (decimalValue << 4) | (hexChar - '0');
            } else if (hexChar >= 'A' && hexChar <= 'F') {
                decimalValue = (decimalValue << 4) | (hexChar - 'A' + 10);
            } else {
                // Handle invalid input by printing an error message and exiting the program.
                System.out.println("Invalid input: " + hexString);
                System.exit(1);
            }
        }

        // Multiply the decimal value of each digit by the appropriate power of 16 and add the results together to obtain the final decimal value.
        int powerOf16 = 1;
        int decimalResult = 0;
        while (decimalValue != 0) {
            int digit = decimalValue & 0xF;
            decimalResult += digit * powerOf16;
            powerOf16 *= 16;
            decimalValue >>>= 4;
        }

        // Display the final decimal value to the user.
        System.out.println(hexString + " in decimal is " + decimalResult);
    }
}

Output:

Enter a hexadecimal number: 1A4B
1A4B in decimal is 6731

Conclusion

In conclusion we can say that converting hexadecimal to decimal is a common task in programming, and Java provides several methods for doing so. The simplest method is to use the built-in Integer.parseInt() method, which handles the conversion for you.

The Math.pow() method can also be used to convert by raising the base (16) to the appropriate power, and bitwise operators can be used to convert individual hexadecimal digits efficiently. It is critical to validate input when working with hexadecimal strings to ensure that it is a valid hexadecimal value.

Java developers can easily convert hexadecimal values to decimal equivalents by using the appropriate approach for the task at hand.