How To Convert Str To Hex In Java

The conversion of string value in Java includes the process that involves converting every string to the hexadecimal value. It is the combination of formation of string values for creating a final hexadecimal value. It is useful for various applications that require decoding and encoding the data for generation of final hexadecimal values.

In the process, the process requires input of string and it contains valid hexadecimal characters. This includes handling errors that may be required during the conversion.

Why Converting Str to Hex in Java is required

Reasons why converting a string to its corresponding hexadecimal value may be required in Java. Here are some of the common use cases:

  • Encoding and decoding of data: The process includes transmission of data on the network.
  • Generation of unique identifiers: This includes values that are used for generation of unique identifiers for objects.
  • Data visualization: The value of Hexadecimal is required for representation of color for development of graphical application and web designing.
  • Hashing and encryption: It includes implementation of hashing and encryption algorithms that provide the value in the form of hexadecimal strings.
  • Debugging: The process of debugging is required for providing the view of the values of variables in hexadecimal format.

Methods for Converting Str to Hex in Java

In the process for Converting string to hexadecimal in Java includes following methods:

  1. Using the Integer class
  2. Using the BigInteger class
  3. Using the StringBuilder class

Have a look at each approaches and learn more about how each method works for converting Str to Hex in Java:

Approach 1: Using the Integer class for Converting Str to Hex in Java

Integer class provides a method called parseInt() that can be used for converting string representation of integer to its corresponding numeric value.

Sample Code:

public class StringToHexExample {
    public static void main(String[] args) {
        // input string
        String str = "Animal";

        // convert string to byte array
        byte[] bytes = str.getBytes();

        // convert byte array to hexadecimal string
        StringBuilder hex = new StringBuilder();
        for (byte b : bytes) {
            hex.append(String.format("%02X", b));
        }

        // output hexadecimal string
        System.out.println("Hexadecimal value of " + str + " is " + hex.toString());
    }
}

Output:

Hexadecimal value of Animal is 416E696D616C

Explanation of Code:

  • We declare a string variable str and set it to the input string “hello.”
  • The use of parseInt() method specifies the radix, which in this case is 16 for hexadecimal.
  • We use the toHexString() method for converting the value from integer to hexadecimal.
  • The final hexadecimal string is output using the System.out object’s println() method.

Approach 2: Using the BigInteger class for Converting Str to Hex in Java

The BigInteger class in Java includes the use of a constructor that takes a string and a radix as arguments. In this method constructor is used for creation of BigInteger Object and  toString() method is used to convert to hexadecimal value.

Sample Code:

import java.math.BigInteger;

public class StringToHexExample {
    public static void main(String[] args) {
        // input string
        String str = "What is your name";

        // convert string to byte array
        byte[] bytes = str.getBytes();

        // create BigInteger object from byte array
        BigInteger bigInt = new BigInteger(1, bytes);

        // convert BigInteger object to hexadecimal string
        String hex = bigInt.toString(16);

        // output hexadecimal string
        System.out.println("Hexadecimal value of " + str + " is " + hex);
    }
}

Output:

Hexadecimal value of ‘What is your name’ is 5768617420697320796f7572206e616d65

Explanation of Code:

  • We declare a string variable str and it is initialized with input string “hello”.
  • A BigInteger object is created from the input string with the use of BigInteger constructor. The next argument is used to specify the radix.
  • toString(int radix) method of the BigInteger class will be used for converting a bigInt object to a hexadecimal string.
  • The output is obtained from the final hexadecimal string with the use of println() method of the System.out object.

Approach 3: Using the StringBuilder class for Converting Str to Hex in Java

The iteration is done for every character in the input string and this is converted to hexadecimal value with the use of toHexString() method. The hexadecimal values can be appended to a StringBuilder object for the formation of the final hexadecimal string.

Sample Code:

public class StringToHexExample {
    public static void main(String[] args) {
        // input string
        String str = "Hello";

        // create StringBuilder object to store hexadecimal value
        StringBuilder hex = new StringBuilder();

        // loop through each character in input string
        for (int i = 0; i < str.length(); i++) {
            // get ASCII value of character
            int ascii = (int) str.charAt(i);

            // convert ASCII value to hexadecimal string
            String hexStr = Integer.toHexString(ascii);

            // append hexadecimal string to StringBuilder object
            hex.append(hexStr);
        }

        // output hexadecimal string
        System.out.println("Hexadecimal value of " + str + " is " + hex);
    }
}

Output:

Hexadecimal value of Hello is 68656c6c6f

Explanation of Code:

  • The StringBuilder object hex that can be used for storing the hexadecimal value of the input string.
  • We loop every character in the input string with the use of a loop.
  • In the loop, the ASCII values of the current character are defined with the use of charAt(int index) and (int) methods.
  • The ASCII value is converted to a hexadecimal string with the use of toHexString(int i).
  • The result is appended to the hexadecimal string and this uses the hex StringBuilder object.
  • After completing the loop, the output is obtained using the println() method of the System.out object.

Best Method for Converting Str to Hex in Java

In the conversion process of String to Hexadecimal, BigInteger class can be considered as the best approach because of following reasons:

  • Potential to handle larger strings: The BigInteger class has the ability to handle big strings of arbitrary length.
  • Support for radix values: The BigInteger class includes use of a constructor that allows specified radix, this can help in making it easy to convert the value to hexadecimal.
  • Considered as a built-in method for easy conversion: It uses the built-in method toString(int radix) that is used for converting a BigInteger object.
  • Java standard library Part: The method is the part of the Java standard library that is widely available and it is well-supported.

Sample Problems for Converting Str to Hex in Java

Sample Problem 1

Create a Java programme that can handle strings of arbitrary length and outputs the resulting hexadecimal value in uppercase. Non-ASCII characters should be handled by the programme and converted to their corresponding hexadecimal values in Unicode format.

Solution:

  • You will have to use the convertToHex method that takes input in the form of String and returns a String output.
  • First, the code checks if the input is null or empty.
  • In the program, the input string is converted to the BigInteger object with the use of a constructor. You can include the use of a radix parameter of 1 that can help in indicating the input that is considered as a byte array.
  • The BigInteger object is converted with the use of toString method.
  • The converted value is padded with leading zeros to ensure that length is twice the length of the value that is taken as string.
  • The code checks the length of the input string. An IllegalArgumentException is thrown that indicates that the input string contains non-hexadecimal characters.
  • Finally, the resulting hexadecimal string is converted to uppercase and returned.
import java.math.BigInteger;

public class StringToHexConverter {
    public static void main(String[] args) {
        String input = "Adam John";
        String hexOutput = convertToHex(input);
        System.out.println(hexOutput);
    }
    
    public static String convertToHex(String input) {
        // Check if input is null or empty, return empty string in such cases
        if (input == null || input.isEmpty()) {
            return "";
        }
        
        // Convert input string to a BigInteger object
        BigInteger bigInteger = new BigInteger(1, input.getBytes());
        
        // Convert BigInteger object to a hexadecimal string
        String hexString = bigInteger.toString(16);
        
        // Pad the hexadecimal string with leading zeros if necessary
        int hexStringLength = (int) Math.ceil(input.length() * 2.0);
        while (hexString.length() < hexStringLength) {
            hexString = "0" + hexString;
        }
        
        // Check if the original input string and the resulting hexadecimal string have the same length
        if (input.length() * 2 != hexString.length()) {
            throw new IllegalArgumentException("Input string contains non-hexadecimal characters.");
        }
        
        return hexString.toUpperCase();
    }
}

Output:

Output: "4164616D204A6F686E"

Sample Problem 2

Create a stringToHexadecimal Java function that accepts a string as input and returns its hexadecimal representation as a string. To create the hexadecimal string, the programme should use the StringBuilder class. Each character in the input string should be converted to its equivalent hexadecimal representation by the programme. Each character’s hexadecimal representation, including leading zeros if necessary to ensure that each representation is two digits long. The final hexadecimal representation should be returned as a string by the function.

Solution:

  • You must implement the stringToHexadecimal function to obtain the string value, which employs the StringBuilder class for hexadecimal representation.
  • StringBuilder object is generated by using a function to construct a hexadecimal string.
  • The function runs through each character in the input string.
  • You must use the Integer.toHexString function to convert the value to hexadecimal notation.
  • The leading zero is appended to the StringBuilder object during the process, ensuring that each representation is two digits long.
  • The function uses the toString method to return the final hexadecimal representation.
  • The main method is used to test the stringToHexadecimal function by sending it the string “Hello, World!” and outputting the output.
public class StringToHexadecimal {
    
    // Function to convert a string to its hexadecimal representation
    public static String stringToHexadecimal(String input) {
        // Create a new StringBuilder object to construct the hexadecimal string
        StringBuilder sb = new StringBuilder();
        
        // Loop through each character in the input string
        for (int i = 0; i < input.length(); i++) {
            // Convert the character to its corresponding hexadecimal representation
            String hex = Integer.toHexString(input.charAt(i));
            
            // Pad the hexadecimal representation with leading zeros if necessary
            if (hex.length() == 1) {
                sb.append("0");
            }
            
            // Append the hexadecimal representation to the StringBuilder object
            sb.append(hex);
        }
        
        // Return the final hexadecimal representation as a string
        return sb.toString();
    }
    
    // Main method for testing the stringToHexadecimal function
    public static void main(String[] args) {
        String input = "Hello, World!";
        String output = stringToHexadecimal(input);
        System.out.println(output);
    }
}

Output:

48656c6c6f2c20576f726c6421

Sample Problem 3

Write a Java program that uses the BigInteger class to convert the input string to a BigInteger object, and then convert the BigInteger object to a hexadecimal string. The program should handle input strings of any length. The resulting hexadecimal string should not have any leading zeros. If the input string is empty or null, the method should return an empty string. The method should throw an illegalArgumentException if the input string contains any non-hexadecimal characters.

Solution:

  • In the program, you will have to define a utility method isHexadecimal() that is used for checking and it includes character for validation of hexadecimal character.
  • Then, you have to implement the convertToHex() method which includes the use of the sample input string “1a3b5c7f9d0a”.
  • After that you will have to implement convertToHex() to check for null or empty input and this returns the empty string when the input found is null.
  • The input is checked and it contains non-hexadecimal characters for iterating over each character.  The input string includes checking and this uses the isHexadecimal(). An IllegalArgumentException is thrown that shows an error message.
  • The program checks the validation of input, it converts the input string to a BigInteger object. With the use of a BigInteger class constructor that includes both radix and string.
  • After that, the Hexadecimal string is returned to uppercase and the method converts the BigInteger object to the hexadecimal string with the use of toString() method.
  • At the end, the main method then prints the resulting hexadecimal string to the console.
import java.math.BigInteger;

public class HexadecimalConverter {

    // A utility method to check if a given character is a valid hexadecimal character
    private static boolean isHexadecimal(char c) {
        return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
    }

    public static String convertToHex(String input) {
        // Check for null or empty input
        if (input == null || input.isEmpty()) {
            return "";
        }

        // Check if input contains any non-hexadecimal characters
        for (int i = 0; i < input.length(); i++) {
            if (!isHexadecimal(input.charAt(i))) {
                throw new IllegalArgumentException("Input contains non-hexadecimal characters");
            }
        }

        // Convert input string to BigInteger object
        BigInteger bigInteger = new BigInteger(input, 16);

        // Convert BigInteger object to hexadecimal string without leading zeros
        return bigInteger.toString(16).toUpperCase();
    }

    public static void main(String[] args) {
        String input = "1a3b5c7f9d0a";
        String hexadecimal = convertToHex(input);
        System.out.println(hexadecimal); // Output: 1A3B5C7F9D0A
    }
}

Output:

1A3B5C7F9D0A

Conclusion

In conclusion, there are multiple ways to convert a string to a hexadecimal value in Java, including using the BigInteger class and the StringBuilder class. When using the BigInteger class, it’s important to handle exceptions and ensure that the resulting hexadecimal value doesn’t have any leading zeros.

Similarly, when using the StringBuilder class, it’s important to handle edge cases, such as empty or null input strings, and to validate the input to ensure that it only contains valid hexadecimal characters.