How To Convert Integer To Hexadecimal In Java

In Java, hexadecimal is a base-16 numbering system, which uses sixteen distinct symbols from 0 to 9 and A to F to represent numbers. An integer can be converted to a hexadecimal string by the representation of the conversion to hexadecimal.

The process includes accepting the integer in the form of input and this returns string value for presenting Hexadecimal value.

What is requirement for converting Integer To Hexadecimal In Java

The conversion of Integer to Hexadecimal in Java is required for multiple reasons, some of reasons includes:

  • Representation of Data: Hexadecimal notation is often used to represent binary data in a more compact and readable format.
  • Color Representation: It can be used for the representation of colours. Hexadecimal notation provides a concise way to represent these RGB values.
  • Memory Representation: Hexadecimal notation is used to represent memory addresses and memory content. This is because memory is typically addressed in hexadecimal notation.
  • Debugging: While debugging and troubleshooting software, particularly when working with low-level code, hexadecimal notation is also utilised.It allows developers to quickly identify memory locations and data values in a more readable format.
  • Encryption: In encryption methods, hexadecimal notation is frequently used to represent encrypted data in a smaller format.

Methods for converting Integer To Hexadecimal In Java

Following are methods that you can use for converting Integer to Hexadecimal in Java, including:

  • Using toHexString() method of Integer class
  • Using String.format() method
  • Using Integer.toHexString() method of BigInteger class
  • Using String.format() method with BigInteger

Let’s find out information about each approach

Approach 1: Using toHexString() method of Integer class to convert Integer To Hexadecimal In Java

This method includes taking the value in the form of integer and returning the hexadecimal value.

Sample Code:

public class IntegerToHexadecimal {

    // Define the main method
    public static void main(String[] args) {

        // Define an integer variable called num and assign it a value of 255
        int num = 255;

        // Call the toHexString method of the Integer class, passing num as an argument
        // Assign the resulting hexadecimal string to a variable called hexString
        String hexString = Integer.toHexString(num);

        // Print the original integer value and its corresponding hexadecimal representation
        System.out.println("Hexadecimal representation of " + num + " is: " + hexString);
    }
}

Output:

Hexadecimal representation of 255 is: ff

Explanation of Code:

  • The code defines a class called IntegerToHexadecimal with a main method.
  • In the main method, an integer value num is defined as 255.
  • The toHexString() method of the Integer class is called, passing the num variable as an argument. The returned value is assigned to a hexString variable.
  • The println() method is used that shows the output to include both the original integer value and its hexadecimal equivalent.

Approach 2: Using String.format() method to convert Integer To Hexadecimal In Java

With the %x format specifier, you can use this technique to convert an integer to hexadecimal.

Sample Code:

public class IntegerToHexadecimal {

    // Define the main method
    public static void main(String[] args) {

        // Define an integer variable called num and assign it a value of 255
        int num = 255;

        // Call the String.format() method, passing the format string "%x" and the num variable as arguments
        // Assign the resulting hexadecimal string to a variable called hexString
        String hexString = String.format("%x", num);

        // Print the original integer value and its corresponding hexadecimal representation
        System.out.println("Hexadecimal representation of " + num + " is: " + hexString);
    }
}

Output:

Hexadecimal representation of 255 is: ff

Explanation of Code:

  • The code defines a class called IntegerToHexadecimal with a main method.
  • In the main method, an integer value num is defined as 255.
  • The String.format() method is called, passing a format string “%x” and the num variable as arguments. The integer value should be transformed to its hexadecimal representation, according to the%x format specifier.
  • The resulting hexadecimal string is assigned to a hexString variable.
  • The result can be displayed with the use of println() method.

Approach 3: Using Integer.toHexString() method of BigInteger class to convert Integer To Hexadecimal In Java

A huge integer value can be represented as a hexadecimal string using this technique.

Sample Code:

import java.math.BigInteger;

// Define a class called IntegerToHexadecimal
public class IntegerToHexadecimal {

    // Define the main method
    public static void main(String[] args) {

        // Define an integer variable called num and assign it a value of 255
        int num = 255;

        // Call the BigInteger constructor, passing the num variable as a string argument
        // The resulting BigInteger object represents the same numeric value as the num variable
        // Then call the toString() method, passing 16 as an argument to convert the BigInteger object to a hexadecimal string
        // Assign the resulting hexadecimal string to a variable called hexString
        String hexString = new BigInteger(String.valueOf(num)).toString(16);

        // Print the original integer value and its corresponding hexadecimal representation
        System.out.println("Hexadecimal representation of " + num + " is: " + hexString);
    }
}

Output:

Hexadecimal representation of 255 is: ff

Explanation of Code:

  • The code defines a class called IntegerToHexadecimal with a main method.
  • The BigInteger class is imported since it is needed to call the toHexString() method.
  • In the main method, an integer value num is defined as 255.
  • The BigInteger constructor is called, passing the num variable as an argument and converting it to a string using String.valueOf(num).
  • The BigInteger class’s function toString() { [native code] }() method is invoked with the argument 16 to signify that the integer should be converted to a hexadecimal string.
  • The resulting hexadecimal string is assigned to a hexString variable.
  • The println() method is used, which provides output to the original integer value along with its hexadecimal representation.

Approach 4: Using String.format() method with BigInteger to convert Integer To Hexadecimal In Java

The BigInteger class now supports using this method to translate huge integer values into hexadecimal string representations.

Sample Code:

import java.math.BigInteger;

// Define a class called IntegerToHexadecimal
public class IntegerToHexadecimal {

    // Define the main method
    public static void main(String[] args) {

        // Define an integer variable called num and assign it a value of 255
        int num = 255;

       // Pass a new BigInteger object created from the num variable as the argument to the format method to convert the integer value to a BigInteger
        // Assign the resulting hexadecimal string to a variable called hexString
        String hexString = String.format("%x", new BigInteger(String.valueOf(num)));

        // Print the original integer value and its corresponding hexadecimal representation
        System.out.println("Hexadecimal representation of " + num + " is: " + hexString);
    }
}

Output:

Hexadecimal representation of 255 is: ff

Explanation of Code:

  • The code defines a class called IntegerToHexadecimal with a main method.
  • The BigInteger class is imported since it is needed to create a BigInteger object to pass to String.format().
  • In the main method, an integer value num is defined as 255.
  • A BigInteger object is created using the BigInteger constructor, passing the num variable as a string argument.
  • The BigInteger object gets converted to a hexadecimal string and this uses the String.format() function.
  • The resulting hexadecimal string is assigned to a hexString variable.

Best Method for converting Integer To Hexadecimal In Java

String.format() method can be chosen has the best method for converting Integer To Hexadecimal:

  • Ease of use: An Integer can be converted to Hexadecimal using just one line of code, and it is very simple to use.
  • Flexibility: You can format the output hexadecimal string to suit your unique requirements.
  • Localization: It provides support for localization, making it easy to generate hexadecimal strings in different languages and formats.
  • Performance: When compared to other Java methods for converting an integer to hexadecimal, it is fairly quick and effective.
  • Consistency: It offers a uniform way to format and output values, making future code maintenance and updates simple.

Sample Problems for converting Integer To Hexadecimal In Java

Sample Problem 1

Write a Java program that generates 10 random integers between 0 and 100 and converts them to hexadecimal strings using the toHexString() method of the Integer class.

Solution:

  • We import the java.util.Random class to generate random integers.
  • We define a main method to run the program.
  • We create a new Random object to generate random integers.
  • We use a for loop to generate 10 random integers between 0 and 100.
  • Inside the loop, we generate a random integer between 0 and 100 using the nextInt() method of the Random object.
  • We convert the random integer to a hexadecimal string using the toHexString() method of the Integer class.
  • We print the random integer and its corresponding hexadecimal string to the console.
import java.util.Random;

public class IntegerToHexadecimal {
    public static void main(String[] args) {
        // Create a Random object to generate random integers
        Random rand = new Random();

        // Generate 10 random integers between 0 and 100 and convert them to hexadecimal strings
        for (int i = 0; i < 10; i++) {
            int randomInt = rand.nextInt(101); // generate a random integer between 0 and 100
            String hexString = Integer.toHexString(randomInt); // convert the random integer to a hexadecimal string
            System.out.println("Random Integer: " + randomInt + ", Hexadecimal String: " + hexString);
        }
    }
}

Output:

Random Integer: 5, Hexadecimal String: 5
Random Integer: 68, Hexadecimal String: 44
Random Integer: 70, Hexadecimal String: 46
Random Integer: 41, Hexadecimal String: 29
Random Integer: 86, Hexadecimal String: 56
Random Integer: 24, Hexadecimal String: 18
Random Integer: 67, Hexadecimal String: 43
Random Integer: 21, Hexadecimal String: 15
Random Integer: 63, Hexadecimal String: 3f
Random Integer: 49, Hexadecimal String: 31

Sample Problem 2

Create a Java programme that uses the toHexString() method of the BigInteger class to generate random BigInteger numbers and convert them to hexadecimal strings.

Solution:

  • We import the java.math.BigInteger and java.security.SecureRandom classes to generate random BigInteger values.
  • We define a main method to run the program.
  • We create a new SecureRandom object to generate random BigInteger values.
  • We use a for loop to generate 5 random BigInteger values.
  • Inside the loop, we generate a random BigInteger value using the BigInteger(int numBits, SecureRandom random) constructor of the BigInteger class. We pass the value 64 as the numBits parameter to generate a BigInteger value with 64 bits.
  • We convert the random BigInteger value to a hexadecimal string using the toString(int radix) method of the BigInteger class. We pass the value 16 as the radix parameter to convert the BigInteger value to a hexadecimal string.
  • We print the random BigInteger value and its corresponding hexadecimal string to the console.
import java.math.BigInteger;
import java.security.SecureRandom;

public class BigIntegerToHexadecimal {
    public static void main(String[] args) {
        // Create a SecureRandom object to generate random BigInteger values
        SecureRandom rand = new SecureRandom();

        // Generate 10 random BigInteger values and convert them to hexadecimal strings
        for (int i = 0; i < 10; i++) {
            BigInteger randomBigInt = new BigInteger(64, rand); // generate a random BigInteger value
            String hexString = randomBigInt.toString(16); // convert the random BigInteger value to a hexadecimal string
            System.out.println("Random BigInteger: " + randomBigInt + ", Hexadecimal String: " + hexString);
        }
    }
}

Output:

Random BigInteger: 912076082718693233, Hexadecimal String: c9f49d786e2fb1
Random BigInteger: 11920194521575524427, Hexadecimal String: a4e954f7f9c40a1b
Random BigInteger: 10042956834508394156, Hexadecimal String: 8b47a6eef2646d4
Random BigInteger: 2355700028333683772, Hexadecimal String: 20d3dc0d3ba3ec
Random BigInteger: 7727476365766851666, Hexadecimal String: 6b2fd424d87ce02

Sample Problem 3

Write a Java method that accepts an array of integers and returns an array of hexadecimal strings using the String.format() method with a BigInteger object.

Solution:

  • We define a method called intToHex that accepts an array of integers as input and returns an array of hexadecimal strings.
  • We create a new String array called hexArr to store the hexadecimal strings.
  • We use a for loop to iterate over the input integer array.
  • Inside the loop, we create a new BigInteger object from the integer value using the BigInteger.valueOf(long val) method of the BigInteger class.
  • We format the BigInteger value as a hexadecimal string using the String.format(String format, Object… args) method of the String class. We pass the format string “%x” to specify that the value should be formatted as a hexadecimal string.
  • We store the formatted hexadecimal string in the hexArr array.
  • After the loop is finished, we return the hexArr array.
  • In the main method, we create an array of integers and call the intToHex method to convert it to an array of hexadecimal strings.
  • We print the original array of integers and the array of hexadecimal strings to the console using a for loop.
import java.math.BigInteger;

public class IntegerToHexadecimal {
    public static String[] intToHex(int[] arr) {
        String[] hexArr = new String[arr.length]; // create a new String array to store the hexadecimal strings

        for (int i = 0; i < arr.length; i++) {
            BigInteger bigInt = BigInteger.valueOf(arr[i]); // create a BigInteger object from the integer value
            hexArr[i] = String.format("%x", bigInt); // format the BigInteger value as a hexadecimal string and store it in the hexArr
        }

        return hexArr; // return the array of hexadecimal strings
    }

    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50}; // create an array of integers
        String[] hexArr = intToHex(arr); // call the intToHex method to convert the array of integers to an array of hexadecimal strings

        // print the original array of integers and the array of hexadecimal strings
        System.out.println("Original Array: ");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }

        System.out.println("\nHexadecimal Array: ");
        for (int i = 0; i < hexArr.length; i++) {
            System.out.print(hexArr[i] + " ");
        }
    }
}

Output:

Original Array: 
10 20 30 40 50 
Hexadecimal Array: 
a 14 1e 28 32 

Sample Problem 4

Write a Java program that takes an integer as input and converts it to a hexadecimal string using the String.format() method. The program should handle negative integers and display the output in uppercase.

Solution:

  • We import the java.util.Scanner class to read the user input from the console.
  • We create a Scanner object called input to read user input.
  • We prompt the user to enter an integer using the System.out.print() method.
  • We read the integer entered by the user using the input.nextInt() method and store it in the decimal variable.
  • We use the String.format() method to convert the decimal integer to a hexadecimal string. The %X format specifier is used to convert the integer to uppercase hexadecimal format.
  • We print the hexadecimal representation of the integer using the System.out.println() method.
import java.util.Scanner;

public class IntegerToHexadecimal {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int decimal = input.nextInt();
        // Use String.format() method to convert decimal to hexadecimal
        String hex = String.format("%X", decimal);

        System.out.println("Hexadecimal representation of " + decimal + " is " + hex);
    }
}

Output:

Enter an integer: 255
Hexadecimal representation of 255 is FF
Enter an integer: -255
Hexadecimal representation of -255 is FFFFFF01

Conclusion

In conclusion, converting an Integer to its hexadecimal representation in Java can be achieved using different methods. The most common methods are using the String.format() method or the toHexString() method of the BigInteger class.

The conversion of an Integer to its hexadecimal representation in Java is a simple and useful task that can be applied in various programming scenarios.