Module java.base
Package java.util

Class Hex


  • public final class Hex
    extends Object
    Converts binary data to and from its hexadecimal (base 16) string representation. It can also generate the classic Unix hexdump(1) format.

    Example usages:

       // Initialize a 16-byte array from a hexadecimal string
       byte[] bytes = Hex.fromHexString("a1a2a3a4a5a6a7a8a9aaabacadaeaf");
    
       // Display the hexadecimal representation of a file's 256-bit hash code
       MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
       System.out.println(
           Hex.toHexString(sha256.digest(Files.readAllBytes(Paths.get("mydata")))));
    
       // Write the printable representation of a file to the standard output stream
       // in 64-byte chunks formatted according to the supplied Formatter function
       Hex.dumpAsStream(Files.readAllBytes(Paths.get("mydata")), 64,
           (offset, chunk, fromIndex, toIndex) ->
               String.format("%d %s",
                   offset / 64 + 1,
                   Hex.toPrintableString(chunk, fromIndex, toIndex)))
           .forEachOrdered(System.out::println);
    
       // Write the standard input stream to the standard output stream in hexdump format
       Hex.dump(System.in, System.out);
     
    Since:
    11
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      static interface  Hex.Formatter
      Represents a function that formats a binary buffer as a hexadecimal string.
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static void dump​(byte[] bytes, int fromIndex, int toIndex, OutputStream out)
      Generates a hexadecimal dump of the contents of a range within the provided byte array and writes it to the provided output stream.
      static void dump​(byte[] bytes, OutputStream out)
      Generates a hexadecimal dump of the contents of the provided byte array and writes it to the provided output stream.
      static void dump​(InputStream in, OutputStream out)
      Generates a hexadecimal dump of the contents of the provided input stream and writes it to the provided output stream.
      static Stream<String> dumpAsStream​(byte[] bytes)
      Generates a dump of the contents of the provided byte array, as a stream of hexadecimal strings in hexdump format.
      static Stream<String> dumpAsStream​(byte[] bytes, int fromIndex, int toIndex, int chunkSize, Hex.Formatter formatter)
      Generates a dump of the contents of a range within the provided byte array, as a stream of formatted hexadecimal strings.
      static Stream<String> dumpAsStream​(InputStream in)
      Generates a dump of the contents of the provided input stream, as a stream of hexadecimal strings in hexdump format.
      static Stream<String> dumpAsStream​(InputStream in, int chunkSize, Hex.Formatter formatter)
      Generates a dump of the contents of the provided input stream, as a stream of formatted hexadecimal strings.
      static byte[] fromHexString​(CharSequence hexString)
      Returns a byte array containing the provided sequence of hexadecimal digits.
      static byte[] fromHexString​(CharSequence hexString, int fromIndex, int toIndex)
      Returns a byte array containing a range within the provided sequence of hexadecimal digits.
      static String toFormattedHexString​(byte[] bytes)
      Returns a formatted hexadecimal string representation of the contents of the provided byte array.
      static String toFormattedHexString​(byte[] bytes, int fromIndex, int toIndex)
      Returns a formatted hexadecimal string representation of the contents of a range within the provided byte array.
      static String toHexString​(byte[] bytes)
      Returns a hexadecimal string representation of the contents of the provided byte array, with no additional formatting.
      static String toHexString​(byte[] bytes, int fromIndex, int toIndex)
      Returns a hexadecimal string representation of a range within the provided byte array, with no additional formatting.
      static String toPrintableString​(byte[] bytes)
      Returns the printable ASCII representation of the contents of the provided byte array.
      static String toPrintableString​(byte[] bytes, int fromIndex, int toIndex)
      Returns the printable ASCII representation of the contents of a range within the provided byte array.
    • Method Detail

      • toHexString

        public static String toHexString​(byte[] bytes)
        Returns a hexadecimal string representation of the contents of the provided byte array, with no additional formatting.

        The binary value is converted to a string comprising pairs of hexadecimal digits that use only the following ASCII characters:

        0123456789abcdef
        Parameters:
        bytes - a binary buffer
        Returns:
        a hexadecimal string representation of the binary buffer. The string length is twice the buffer length.
        Throws:
        NullPointerException - if bytes is null
      • toHexString

        public static String toHexString​(byte[] bytes,
                                         int fromIndex,
                                         int toIndex)
        Returns a hexadecimal string representation of a range within the provided byte array, with no additional formatting.

        The binary value is converted to a string comprising pairs of hexadecimal digits that use only the following ASCII characters:

        0123456789abcdef
        The range to be converted extends from index fromIndex, inclusive, to index toIndex, exclusive. (If fromIndex==toIndex, the range to be converted is empty.)
        Parameters:
        bytes - a binary buffer
        fromIndex - the index of the first byte (inclusive) to be converted
        toIndex - the index of the last byte (exclusive) to be converted
        Returns:
        a hexadecimal string representation of the binary buffer. The string length is twice the number of bytes converted.
        Throws:
        NullPointerException - if bytes is null
        IllegalArgumentException - if fromIndex > toIndex
        ArrayIndexOutOfBoundsException - if fromIndex < 0 or toIndex > bytes.length
      • toFormattedHexString

        public static String toFormattedHexString​(byte[] bytes)
        Returns a formatted hexadecimal string representation of the contents of the provided byte array.

        The binary value is converted to a string in the canonical hexdump format of two columns of eight space-separated pairs of hexadecimal digits that use only the following ASCII characters:

        0123456789abcdef

        If the number of bytes to be converted is greater than 16 then line-separator characters are inserted after each 16-byte chunk. If the final chunk is less than 16 then it is padded with spaces to match the length of the preceding chunks. The general output format is as follows:

         00 11 22 33 44 55 66 77  88 99 aa bb cc dd ee ff
         
        Parameters:
        bytes - a binary buffer
        Returns:
        a formatted hexadecimal string representation of the binary buffer
        Throws:
        NullPointerException - if bytes is null
      • toFormattedHexString

        public static String toFormattedHexString​(byte[] bytes,
                                                  int fromIndex,
                                                  int toIndex)
        Returns a formatted hexadecimal string representation of the contents of a range within the provided byte array.

        The binary value is converted to a string in the canonical hexdump format of two columns of eight space-separated pairs of hexadecimal digits that use only the following ASCII characters:

        0123456789abcdef

        The range to be converted extends from index fromIndex, inclusive, to index toIndex, exclusive. (If fromIndex==toIndex, the range to be converted is empty.)

        If the number of bytes to be converted is greater than 16 then line-separator characters are inserted after each 16-byte chunk. If the final chunk is less than 16 then it is padded with spaces to match the length of the preceding chunks. The general output format is as follows:

         00 11 22 33 44 55 66 77  88 99 aa bb cc dd ee ff
         
        Parameters:
        bytes - a binary buffer
        fromIndex - the index of the first byte (inclusive) to be converted
        toIndex - the index of the last byte (exclusive) to be converted
        Returns:
        a formatted hexadecimal string representation of the binary buffer
        Throws:
        NullPointerException - if bytes is null
        IllegalArgumentException - if fromIndex > toIndex
        ArrayIndexOutOfBoundsException - if fromIndex < 0 or toIndex > bytes.length
      • toPrintableString

        public static String toPrintableString​(byte[] bytes)
        Returns the printable ASCII representation of the contents of the provided byte array.

        The binary value is converted to a string comprising printable ASCII characters, or '.' if the byte maps to a non-printable character. A non-printable character is one outside of the ASCII range ' ' through '~' ('\u0020' through '\u007E').

        Parameters:
        bytes - a binary buffer
        Returns:
        a printable ASCII representation of the binary buffer
        Throws:
        NullPointerException - if bytes is null
      • toPrintableString

        public static String toPrintableString​(byte[] bytes,
                                               int fromIndex,
                                               int toIndex)
        Returns the printable ASCII representation of the contents of a range within the provided byte array.

        The binary value is converted to a string comprising printable ASCII characters, or '.' if the byte maps to a non-printable character. A non-printable character is one outside of the ASCII range ' ' through '~' ('\u0020' through '\u007E').

        Parameters:
        bytes - a binary buffer
        fromIndex - the index of the first byte (inclusive) to be converted
        toIndex - the index of the last byte (exclusive) to be converted
        Returns:
        a printable ASCII representation of the binary buffer
        Throws:
        NullPointerException - if bytes is null
        IllegalArgumentException - if fromIndex > toIndex
        ArrayIndexOutOfBoundsException - if fromIndex < 0 or toIndex > bytes.length
      • fromHexString

        public static byte[] fromHexString​(CharSequence hexString)
        Returns a byte array containing the provided sequence of hexadecimal digits. The sequence may be prefixed with the hexadecimal indicator "0x".

        The binary value is generated from pairs of hexadecimal digits that use only the following ASCII characters:

        0123456789abcdefABCDEF
        Parameters:
        hexString - an even numbered sequence of hexadecimal digits
        Returns:
        a binary buffer
        Throws:
        IllegalArgumentException - if hexString has an odd number of digits or contains an illegal hexadecimal character
        NullPointerException - if hexString is null
      • fromHexString

        public static byte[] fromHexString​(CharSequence hexString,
                                           int fromIndex,
                                           int toIndex)
        Returns a byte array containing a range within the provided sequence of hexadecimal digits. The sequence may be prefixed with the hexadecimal indicator "0x".

        The binary value is generated from pairs of hexadecimal digits that use only the following ASCII characters:

        0123456789abcdefABCDEF
        Parameters:
        hexString - an even numbered sequence of hexadecimal digits
        fromIndex - the index of the first digit (inclusive) to be converted
        toIndex - the index of the last digit (exclusive) to be converted
        Returns:
        a binary buffer
        Throws:
        IllegalArgumentException - if hexString has an odd number of digits or contains an illegal hexadecimal character, or if fromIndex > toIndex
        NullPointerException - if hexString is null
        ArrayIndexOutOfBoundsException - if fromIndex < 0 or toIndex > hexString.length()
      • dumpAsStream

        public static Stream<String> dumpAsStream​(InputStream in)
        Generates a dump of the contents of the provided input stream, as a stream of hexadecimal strings in hexdump format. This method outputs the same format as dump(byte[],OutputStream), without the line-separator characters.

        If the input is not a multiple of 16 bytes then the final chunk will be shorter than the preceding chunks.

        On return, the input stream will be at end-of-stream. This method does not close the input stream and may block indefinitely reading from it. The behavior for the case where it is asynchronously closed, or the thread interrupted, is highly input stream specific, and therefore not specified.

        If an I/O error occurs reading from the input stream then it may not be at end-of-stream and may be in an inconsistent state. It is strongly recommended that the input stream be promptly closed if an I/O error occurs.

        Parameters:
        in - the input stream, non-null
        Returns:
        a stream of hexadecimal strings
      • dumpAsStream

        public static Stream<String> dumpAsStream​(InputStream in,
                                                  int chunkSize,
                                                  Hex.Formatter formatter)
        Generates a dump of the contents of the provided input stream, as a stream of formatted hexadecimal strings. Each string is formatted according to the formatter function, if present. Otherwise, this method outputs the same format as dump(byte[],OutputStream), without the line separator characters.

        On return, the input stream will be at end-of-stream. This method does not close the input stream and may block indefinitely reading from it. The behavior for the case where it is asynchronously closed, or the thread interrupted, is highly input stream specific, and therefore not specified.

        If an I/O error occurs reading from the input stream then it may not be at end-of-stream and may be in an inconsistent state. It is strongly recommended that the input stream be promptly closed if an I/O error occurs. If an error occurs in the formatter then an unchecked exception will be thrown from the underlying Stream method.

        Parameters:
        in - the input stream, non-null
        chunkSize - the number of bytes-per-chunk (typically 16)
        formatter - a hexdump formatting function, or null
        Returns:
        a stream of hexadecimal strings
        Throws:
        NullPointerException - if in is null
      • dumpAsStream

        public static Stream<String> dumpAsStream​(byte[] bytes)
        Generates a dump of the contents of the provided byte array, as a stream of hexadecimal strings in hexdump format. This method outputs the same format as dump(byte[],OutputStream), without the line separator characters.

        If the input is not a multiple of 16 bytes then the final chunk will be shorter than the preceding chunks.

        Parameters:
        bytes - a binary buffer, assumed to be unmodified during use
        Returns:
        a stream of hexadecimal strings
        Throws:
        NullPointerException - if bytes is null
      • dumpAsStream

        public static Stream<String> dumpAsStream​(byte[] bytes,
                                                  int fromIndex,
                                                  int toIndex,
                                                  int chunkSize,
                                                  Hex.Formatter formatter)
        Generates a dump of the contents of a range within the provided byte array, as a stream of formatted hexadecimal strings. Each string is formatted according to the formatter function, if present. Otherwise, this method outputs the same format as dump(byte[],OutputStream), without the line separator characters.

        The range to be converted extends from index fromIndex, inclusive, to index toIndex, exclusive. (If fromIndex==toIndex, the range to be converted is empty.) If the input is not a multiple of chunkSize then the final chunk will be shorter than the preceding chunks. If an error occurs in the formatter then an unchecked exception will be thrown from the underlying Stream method.

        Parameters:
        bytes - a binary buffer, assumed to be unmodified during use
        fromIndex - the index of the first byte (inclusive) to be converted
        toIndex - the index of the last byte (exclusive) to be converted
        chunkSize - the number of bytes-per-chunk (typically 16)
        formatter - a hexdump formatting function, or null
        Returns:
        a stream of hexadecimal strings
        Throws:
        NullPointerException - if bytes is null
        IllegalArgumentException - if fromIndex > toIndex
        ArrayIndexOutOfBoundsException - if fromIndex < 0 or toIndex > bytes.length
      • dump

        public static void dump​(byte[] bytes,
                                OutputStream out)
                         throws IOException
        Generates a hexadecimal dump of the contents of the provided byte array and writes it to the provided output stream. This method behaves as if:
        
             Hex.dumpAsStream(bytes, 16,
                 (offset, chunk, from, to) ->
                     String.format("%08x  %s  |%s|",
                         offset,
                         Hex.toFormattedHexString(chunk, from, to),
                         Hex.toPrintableString(chunk, from, to)))
                 .forEachOrdered(PrintStream::println);
         

        This method does not close the output stream and may block indefinitely writing to it. The behavior for the case where it is asynchronously closed, or the thread interrupted, is highly output stream specific, and therefore not specified.

        If an I/O error occurs writing to the output stream, then it may be in an inconsistent state. It is strongly recommended that the output stream be promptly closed if an I/O error occurs.

        Parameters:
        bytes - the binary buffer, assumed to be unmodified during use
        out - the output stream, non-null
        Throws:
        IOException - if an I/O error occurs when writing
        NullPointerException - if bytes or out is null
      • dump

        public static void dump​(byte[] bytes,
                                int fromIndex,
                                int toIndex,
                                OutputStream out)
                         throws IOException
        Generates a hexadecimal dump of the contents of a range within the provided byte array and writes it to the provided output stream. This method outputs the same format as dump(byte[],OutputStream).

        The range to be converted extends from index fromIndex, inclusive, to index toIndex, exclusive. (If fromIndex==toIndex, the range to be converted is empty.)

        This method does not close the output stream and may block indefinitely writing to it. The behavior for the case where it is asynchronously closed, or the thread interrupted, is highly output stream specific, and therefore not specified.

        If an I/O error occurs writing to the output stream, then it may be in an inconsistent state. It is strongly recommended that the output stream be promptly closed if an I/O error occurs.

        Parameters:
        bytes - the binary buffer, assumed to be unmodified during use
        fromIndex - the index of the first byte (inclusive) to be converted
        toIndex - the index of the last byte (exclusive) to be converted
        out - the output stream, non-null
        Throws:
        IOException - if an I/O error occurs when writing
        NullPointerException - if bytes or out is null
        IllegalArgumentException - if fromIndex > toIndex
        ArrayIndexOutOfBoundsException - if fromIndex < 0 or toIndex > bytes.length
      • dump

        public static void dump​(InputStream in,
                                OutputStream out)
                         throws IOException
        Generates a hexadecimal dump of the contents of the provided input stream and writes it to the provided output stream. This method outputs the same format as dump(byte[],OutputStream).

        Reads all bytes from the input stream. On return, the input stream will be at end-of-stream. This method does not close either stream and may block indefinitely reading from the input stream, or writing to the output stream. The behavior for the case where the input and/or output stream is asynchronously closed, or the thread interrupted, is highly input stream and output stream specific, and therefore not specified.

        If an I/O error occurs reading from the input stream or writing to the output stream, then it may do so after some bytes have been read or written. Consequently the input stream may not be at end-of-stream and one, or both, streams may be in an inconsistent state. It is strongly recommended that both streams be promptly closed if an I/O error occurs.

        Parameters:
        in - the input stream, non-null
        out - the output stream, non-null
        Throws:
        IOException - if an I/O error occurs when reading or writing
        NullPointerException - if in or out is null