Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaHexFormat in Java

HexFormat in Java

HexFormat is a mechanism that can convert bytes to hexadecimal strings and vice versa. It can add extra formatting such as symbols, commas, or brackets to the output. Two versions of HexFormat can be used, one with a specific symbol and one without any symbols. Other options can be set using various methods like with prefix (), with suffix (), with delimiter (), with uppercase (), and with lowercase (). It can also convert primitive types like numbers to hexadecimal strings and back.

If you have a series of bytes, HexFormat can convert them into a string of numbers and letters like “1a2b3c4d”. Conversely, if you have a string of numbers and letters like that, HexFormat can convert them back into bytes. For example, if you use the format () method with a byte array, it will return a string that looks like “0x1a, 0x2b, 0x3c, 0x4d”. If you use the parseHex() method with that same string, it will convert it back into a byte array. HexFormat is a mechanism that is commonly used in computer programming and helps convert data between different formats. It is designed to be flexible and customizable to handle a wide variety of situations.

Example of how to use hexadecimal in java:

Java




import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Formatter;
  
public class HexFormatExample {
    public static void main(String[] args)
    {
  
        // Convert byte array to hexadecimal string
        byte[] bytes = "Hello, world!".getBytes(
            StandardCharsets.UTF_8);
        StringBuilder hexString = new StringBuilder();
        try (Formatter formatter
             = new Formatter(hexString)) {
            for (byte b : bytes) {
                formatter.format("%02x:", b);
            }
            hexString.deleteCharAt(hexString.length() - 1);
        }
        System.out.println(
            hexString); // output:
                        // "48:65:6c:6c:6f:2c:20:77:6f:72:6c:64:21"
  
        // Convert hexadecimal string to byte array
        String[] hexValues
            = hexString.toString().split(":");
        byte[] parsedBytes = new byte[hexValues.length];
        for (int i = 0; i < hexValues.length; i++) {
            parsedBytes[i]
                = (byte)Integer.parseInt(hexValues[i], 16);
        }
        System.out.println(Arrays.equals(
            bytes, parsedBytes)); // output: true
    }
}


Output:

48:65:6c:6c:6f:2c:20:77:6f:72:6c:64:21
true

Code Explanation:

This Java code demonstrates how to convert a byte array to a hexadecimal string and back again. Here is a brief explanation of each part of the code.

  1. import java.nio.charset.StandardCharsets – This imports the StandardCharsets class which provides constants for character encodings.
  2. import java.util.Arrays – This imports the Arrays class which provides methods for manipulating arrays.
  3. import java.util.Formatter – This imports the Formatter class which provides support for formatted output.
  4. public class HexFormatExample – This defines a public class called HexFormatExample.
  5. public static void main(String[] args) – This defines a public static method called main which takes an array of strings as its argument.
  6. byte[] bytes = “Hello, world!”.getBytes(StandardCharsets.UTF_8); – This creates a byte array containing the UTF-8 encoded bytes of the string “Hello, world!”.
  7. StringBuilder hexString = new StringBuilder(); – This creates a StringBuilder object to store the hexadecimal string.
  8. try (Formatter formatter = new Formatter(hexString)) – This creates a Formatter object that writes to the StringBuilder object hexString.
  9. for (byte b : bytes) { formatter.format(“%02x:”, b); } – This formats each byte in the bytes array as a two-digit hexadecimal number with a colon separator, and appends it to the hexString object.
  10. hexString.deleteCharAt(hexString.length() – 1); – This removes the trailing colon separator from the hexString object.
  11. System.out.println(hexString); – This prints the hexadecimal string to the console.
    String[] hexValues = hexString.toString().split(“:”); – This splits the hexadecimal string into an array of strings, where each string is a two-digit hexadecimal number.
  12. byte[] parsedBytes = new byte[hexValues.length]; – This creates a new byte array to store the parsed bytes.
  13. for (int i = 0; i < hexValues.length; i++) { parsedBytes[i] = (byte) Integer.parseInt(hexValues[i], 16); } – This loops through the array of hexadecimal
  14. strings and parses each string as a hexadecimal number, which is then cast to a byte and stored in the parsedBytes array.
  15. System.out.println(Arrays.equals(bytes, parsedBytes)); – This compares the original bytes array with the parsedBytes array and prints true if they are equal.

HexFormat is a way to represent numerical values in hexadecimal (base 16) formats. 

Decimal Hex
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 A
11 B
12 C
13 D
14 E
15 F

Example:

1101 1010 this is binary no  and to represent this no in hex, 
we can write it as the hexa no DA. but why ? 
as D represents 13 and A represents 10 in hexadecimal. 

It is a convenient way to represent binary data such as colors, cryptographic keys, and network addresses.

Decimal to hex in Java:

  • String.format() method is used.
  • format specifier:

%x  is used to represent an integer in hexadecimal format. %02x represents an integer in hexadecimal format with a leading zero.

Here is an example that shows how to use Hexformat in Java:

Java




/*package whatever //do not write package name here */
  
import java.io.*;
import java.util.Arrays;
class GFG {
    public static void main(String[] args)
    {
        // example 1
        int num1 = 13;
        System.out.println("Decimal: " + num1);
        System.out.println("Hexadecimal: "
                           + String.format("%02x", num1));
        // example 2
        int num2 = 1024;
        System.out.println("Decimal: " + num2);
        System.out.println("Hexadecimal: "
                           + String.format("%x", num2));
        // example 3  : byte to hexadecimal
        byte[] bytes
            = { 0x1a, 0x2b, 0x3c, 0x4d, 0x5e, 0x6f };
        System.out.println("Bytes: "
                           + Arrays.toString(bytes));
        System.out.println("Hexadecimal: "
                           + bytesToHex(bytes));
    }
  
    // utility method to convert a byte array to a
    // hexadecimal string
    public static String bytesToHex(byte[] bytes)
    {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}


Output:

Decimal: 13
Hexadecimal: 0d
Decimal: 1024
Hexadecimal: 400
Bytes: [26, 43, 60, 77, 94, 111]
Hexadecimal: 1a2b3c4d5e6f

Code Explanation:  

  • In the example, we first convert an integer num1 to a hexadecimal string with a leading zero using the format specifier %02x. 
  • We then convert another integer num2 to a hexadecimal string without a leading zero using the format specifier %x.
  • Finally, we convert a byte array bytes to a hexadecimal string using the utility method bytesToHex().
  • Which iterates over each byte in the array and converts it to a two-digit hexadecimal string using the %02x format specifier. 
  • The resulting strings are then concatenated into a single string using a StringBuilder.
RELATED ARTICLES

Most Popular

Recent Comments