Class HexFormat

java.lang.Object
java.util.HexFormat

public final classHexFormatextendsObject
HexFormat converts between bytes and chars and hex-encoded strings which may include additional formatting markup such as prefixes, suffixes, and delimiters.

There are two factories ofHexFormat with preset parametersof() andofDelimiter(delimiter). For other parameter combinations thewithXXX methods return copies ofHexFormat modifiedwithPrefix(String),withSuffix(String),withDelimiter(String) or choice ofwithUpperCase() orwithLowerCase() parameters.

For primitive to hexadecimal string conversions thetoHexDigits methods includetoHexDigits(byte),toHexDigits(int), andtoHexDigits(long), etc. The default is to use lowercase characters"0-9","a-f". For conversions producing uppercase hexadecimal the characters are"0-9","A-F". Only theHexFormat.isUpperCase() parameter is considered; the delimiter, prefix and suffix are not used.

For hexadecimal string to primitive conversions thefromHexDigits methods includefromHexDigits(string),fromHexDigitsToLong(string), andfromHexDigit(int) converts a single character or codepoint. For conversions from hexadecimal characters the digits and uppercase and lowercase characters in"0-9", "a-f", and "A-F" are converted to corresponding values0-15. The delimiter, prefix, suffix, and uppercase parameters are not used.

For byte array to formatted hexadecimal string conversions theformatHex methods includeformatHex(byte[]) andformatHex(Appendable, byte[]). The formatted output is a string or is appended to anAppendable such asStringBuilder orPrintStream. Each byte value is formatted as the prefix, two hexadecimal characters from the uppercase or lowercase digits, and the suffix. A delimiter follows each formatted value, except the last. For conversions producing uppercase hexadecimal strings usewithUpperCase().

For formatted hexadecimal string to byte array conversions theparseHex methods includeparseHex(CharSequence) andparseHex(char[], offset, length). Each byte value is parsed from the prefix, two case insensitive hexadecimal characters, and the suffix. A delimiter follows each formatted value, except the last.

API Note:
For example, an individual byte is converted to a string of hexadecimal digits usingtoHexDigits(int) and converted from a string to a primitive value usingfromHexDigits(string).
     HexFormat hex = HexFormat.of();     byte b = 127;     String byteStr = hex.toHexDigits(b);     byte byteVal = (byte)hex.fromHexDigits(byteStr);     assert(byteStr.equals("7f"));     assert(b == byteVal);     // The hexadecimal digits are: "7f"

For a comma (", ") separated format with a prefix ("#") using lowercase hex digits theHexFormat is:

     HexFormat commaFormat = HexFormat.ofDelimiter(", ").withPrefix("#");     byte[] bytes = {0, 1, 2, 3, 124, 125, 126, 127};     String str = commaFormat.formatHex(bytes);     byte[] parsed = commaFormat.parseHex(str);     assert(Arrays.equals(bytes, parsed));     // The formatted string is: "#00, #01, #02, #03, #7c, #7d, #7e, #7f"

For a fingerprint of byte values that uses the delimiter colon (":") and uppercase characters theHexFormat is:

     HexFormat formatFingerprint = HexFormat.ofDelimiter(":").withUpperCase();     byte[] bytes = {0, 1, 2, 3, 124, 125, 126, 127};     String str = formatFingerprint.formatHex(bytes);     byte[] parsed = formatFingerprint.parseHex(str);     assert(Arrays.equals(bytes, parsed));     // The formatted string is: "00:01:02:03:7C:7D:7E:7F"

This is avalue-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances ofHexFormat may have unpredictable results and should be avoided. Theequals method should be used for comparisons.

This class is immutable and thread-safe.

Unless otherwise noted, passing a null argument to any method will cause aNullPointerException to be thrown.

Since:
17
  • Method Summary

    Modifier and Type
    Method
    Description
    Returns the delimiter between hexadecimal values in formatted hexadecimal strings.
    boolean
    Returnstrue if the other object is aHexFormat with the same parameters.
    formatHex(byte[] bytes)
    Returns a hexadecimal string formatted from a byte array.
    formatHex(byte[] bytes, int fromIndex, int toIndex)
    Returns a hexadecimal string formatted from a byte array range.
    <A extendsAppendable>
    A
    formatHex(A out, byte[] bytes)
    Appends formatted hexadecimal strings from a byte array to theAppendable.
    <A extendsAppendable>
    A
    formatHex(A out, byte[] bytes, int fromIndex, int toIndex)
    Appends formatted hexadecimal strings from a byte array range to theAppendable.
    static int
    fromHexDigit(int ch)
    Returns the value for the hexadecimal character or codepoint.
    static int
    Returns theint value parsed from a string of up to eight hexadecimal characters.
    static int
    fromHexDigits(CharSequence string, int fromIndex, int toIndex)
    Returns theint value parsed from a string range of up to eight hexadecimal characters.
    static long
    Returns the long value parsed from a string of up to sixteen hexadecimal characters.
    static long
    fromHexDigitsToLong(CharSequence string, int fromIndex, int toIndex)
    Returns the long value parsed from a string range of up to sixteen hexadecimal characters.
    int
    Returns a hashcode for thisHexFormat.
    static boolean
    isHexDigit(int ch)
    Returnstrue if the character is a valid hexadecimal character or codepoint.
    boolean
    Returnstrue if the hexadecimal digits are uppercase, otherwisefalse.
    staticHexFormat
    of()
    Returns a hexadecimal formatter with no delimiter and lowercase characters.
    staticHexFormat
    ofDelimiter(String delimiter)
    Returns a hexadecimal formatter with the delimiter and lowercase characters.
    byte[]
    parseHex(char[] chars, int fromIndex, int toIndex)
    Returns a byte array containing hexadecimal values parsed from a range of the character array.
    byte[]
    Returns a byte array containing hexadecimal values parsed from the string.
    byte[]
    parseHex(CharSequence string, int fromIndex, int toIndex)
    Returns a byte array containing hexadecimal values parsed from a range of the string.
    Returns the prefix used for each hexadecimal value in formatted hexadecimal strings.
    Returns the suffix used for each hexadecimal value in formatted hexadecimal strings.
    toHexDigits(byte value)
    Returns the two hexadecimal characters for thebyte value.
    toHexDigits(char value)
    Returns the four hexadecimal characters for thechar value.
    toHexDigits(int value)
    Returns the eight hexadecimal characters for theint value.
    toHexDigits(long value)
    Returns the sixteen hexadecimal characters for thelong value.
    toHexDigits(long value, int digits)
    Returns up to sixteen hexadecimal characters for thelong value.
    toHexDigits(short value)
    Returns the four hexadecimal characters for theshort value.
    <A extendsAppendable>
    A
    toHexDigits(A out, byte value)
    Appends two hexadecimal characters for the byte value to theAppendable.
    char
    toHighHexDigit(int value)
    Returns the hexadecimal character for the high 4 bits of the value considering it to be a byte.
    char
    toLowHexDigit(int value)
    Returns the hexadecimal character for the low 4 bits of the value considering it to be a byte.
    Returns a description of the formatter parameters for uppercase, delimiter, prefix, and suffix.
    withDelimiter(String delimiter)
    Returns a copy of thisHexFormat with the delimiter.
    Returns a copy of thisHexFormat to use lowercase hexadecimal characters.
    Returns a copy of thisHexFormat with the prefix.
    Returns a copy of thisHexFormat with the suffix.
    Returns a copy of thisHexFormat to use uppercase hexadecimal characters.

    Methods declared in class java.lang.Object

    clone,finalize,getClass,notify,notifyAll,wait,wait,wait
  • Method Details

    • of

      public static HexFormat of()
      Returns a hexadecimal formatter with no delimiter and lowercase characters. The delimiter, prefix, and suffix are empty. The methodswithDelimiter,withUpperCase,withLowerCase,withPrefix, andwithSuffix return copies of formatters with new parameters.
      Returns:
      a hexadecimal formatter with no delimiter and lowercase characters
    • ofDelimiter

      public static HexFormat ofDelimiter(String delimiter)
      Returns a hexadecimal formatter with the delimiter and lowercase characters. The prefix and suffix are empty. The methodswithDelimiter,withUpperCase,withLowerCase,withPrefix, andwithSuffix return copies of formatters with new parameters.
      Parameters:
      delimiter - a delimiter, non-null, may be empty
      Returns:
      aHexFormat with the delimiter and lowercase characters
    • withDelimiter

      public HexFormat withDelimiter(String delimiter)
      Returns a copy of thisHexFormat with the delimiter.
      Parameters:
      delimiter - the delimiter, non-null, may be empty
      Returns:
      a copy of thisHexFormat with the delimiter
    • withPrefix

      public HexFormat withPrefix(String prefix)
      Returns a copy of thisHexFormat with the prefix.
      Parameters:
      prefix - a prefix, non-null, may be empty
      Returns:
      a copy of thisHexFormat with the prefix
    • withSuffix

      public HexFormat withSuffix(String suffix)
      Returns a copy of thisHexFormat with the suffix.
      Parameters:
      suffix - a suffix, non-null, may be empty
      Returns:
      a copy of thisHexFormat with the suffix
    • withUpperCase

      public HexFormat withUpperCase()
      Returns a copy of thisHexFormat to use uppercase hexadecimal characters. The uppercase hexadecimal characters are"0-9", "A-F".
      Returns:
      a copy of thisHexFormat with uppercase hexadecimal characters
    • withLowerCase

      public HexFormat withLowerCase()
      Returns a copy of thisHexFormat to use lowercase hexadecimal characters. The lowercase hexadecimal characters are"0-9", "a-f".
      Returns:
      a copy of thisHexFormat with lowercase hexadecimal characters
    • delimiter

      public String delimiter()
      Returns the delimiter between hexadecimal values in formatted hexadecimal strings.
      Returns:
      the delimiter, non-null, may be empty""
    • prefix

      public String prefix()
      Returns the prefix used for each hexadecimal value in formatted hexadecimal strings.
      Returns:
      the prefix, non-null, may be empty""
    • suffix

      public String suffix()
      Returns the suffix used for each hexadecimal value in formatted hexadecimal strings.
      Returns:
      the suffix, non-null, may be empty""
    • isUpperCase

      public boolean isUpperCase()
      Returnstrue if the hexadecimal digits are uppercase, otherwisefalse.
      Returns:
      true if the hexadecimal digits are uppercase, otherwisefalse
    • formatHex

      public String formatHex(byte[] bytes)
      Returns a hexadecimal string formatted from a byte array. Each byte value is formatted as the prefix, two hexadecimal charactersselected from uppercase or lowercase digits, and the suffix. A delimiter follows each formatted value, except the last. The behavior is equivalent toformatHex(bytes, 0, bytes.length)).
      Parameters:
      bytes - a non-null array of bytes
      Returns:
      a string hexadecimal formatting of the byte array
    • formatHex

      public String formatHex(byte[] bytes, int fromIndex, int toIndex)
      Returns a hexadecimal string formatted from a byte array range. Each byte value is formatted as the prefix, two hexadecimal charactersselected from uppercase or lowercase digits, and the suffix. A delimiter follows each formatted value, except the last.
      Parameters:
      bytes - a non-null array of bytes
      fromIndex - the initial index of the range, inclusive
      toIndex - the final index of the range, exclusive
      Returns:
      a string hexadecimal formatting each byte of the array range
      Throws:
      IndexOutOfBoundsException - if the array range is out of bounds
    • formatHex

      public <A extendsAppendable> A formatHex(A out, byte[] bytes)
      Appends formatted hexadecimal strings from a byte array to theAppendable. Each byte value is formatted as the prefix, two hexadecimal charactersselected from uppercase or lowercase digits, and the suffix. A delimiter follows each formatted value, except the last. The formatted hexadecimal strings are appended in zero or more calls to theAppendable methods.
      Type Parameters:
      A - The type ofAppendable
      Parameters:
      out - anAppendable, non-null
      bytes - a byte array
      Returns:
      theAppendable
      Throws:
      UncheckedIOException - if an I/O exception occurs appending to the output
    • formatHex

      public <A extendsAppendable> A formatHex(A out, byte[] bytes, int fromIndex, int toIndex)
      Appends formatted hexadecimal strings from a byte array range to theAppendable. Each byte value is formatted as the prefix, two hexadecimal charactersselected from uppercase or lowercase digits, and the suffix. A delimiter follows each formatted value, except the last. The formatted hexadecimal strings are appended in zero or more calls to theAppendable methods.
      Type Parameters:
      A - The type ofAppendable
      Parameters:
      out - anAppendable, non-null
      bytes - a byte array, non-null
      fromIndex - the initial index of the range, inclusive
      toIndex - the final index of the range, exclusive.
      Returns:
      theAppendable
      Throws:
      IndexOutOfBoundsException - if the array range is out of bounds
      UncheckedIOException - if an I/O exception occurs appending to the output
    • parseHex

      public byte[] parseHex(CharSequence string)
      Returns a byte array containing hexadecimal values parsed from the string. Each byte value is parsed from the prefix, two case insensitive hexadecimal characters, and the suffix. A delimiter follows each formatted value, except the last. The delimiters, prefixes, and suffixes strings must be present; they may be empty strings. A valid string consists only of the above format.
      Parameters:
      string - a string containing the byte values with prefix, hexadecimal digits, suffix, and delimiters
      Returns:
      a byte array with the values parsed from the string
      Throws:
      IllegalArgumentException - if the prefix or suffix is not present for each byte value, the byte values are not hexadecimal characters, or if the delimiter is not present after all but the last byte value
    • parseHex

      public byte[] parseHex(CharSequence string, int fromIndex, int toIndex)
      Returns a byte array containing hexadecimal values parsed from a range of the string. Each byte value is parsed from the prefix, two case insensitive hexadecimal characters, and the suffix. A delimiter follows each formatted value, except the last. The delimiters, prefixes, and suffixes strings must be present; they may be empty strings. A valid string consists only of the above format.
      Parameters:
      string - a string range containing hexadecimal digits, delimiters, prefix, and suffix.
      fromIndex - the initial index of the range, inclusive
      toIndex - the final index of the range, exclusive.
      Returns:
      a byte array with the values parsed from the string range
      Throws:
      IllegalArgumentException - if the prefix or suffix is not present for each byte value, the byte values are not hexadecimal characters, or if the delimiter is not present after all but the last byte value
      IndexOutOfBoundsException - if the string range is out of bounds
    • parseHex

      public byte[] parseHex(char[] chars, int fromIndex, int toIndex)
      Returns a byte array containing hexadecimal values parsed from a range of the character array. Each byte value is parsed from the prefix, two case insensitive hexadecimal characters, and the suffix. A delimiter follows each formatted value, except the last. The delimiters, prefixes, and suffixes strings must be present; they may be empty strings. A valid character array range consists only of the above format.
      Parameters:
      chars - a character array range containing an even number of hexadecimal digits, delimiters, prefix, and suffix.
      fromIndex - the initial index of the range, inclusive
      toIndex - the final index of the range, exclusive.
      Returns:
      a byte array with the values parsed from the character array range
      Throws:
      IllegalArgumentException - if the prefix or suffix is not present for each byte value, the byte values are not hexadecimal characters, or if the delimiter is not present after all but the last byte value
      IndexOutOfBoundsException - if the character array range is out of bounds
    • toLowHexDigit

      public char toLowHexDigit(int value)
      Returns the hexadecimal character for the low 4 bits of the value considering it to be a byte. If the parameterisUpperCase() istrue the character returned for values10-15 is uppercase"A-F", otherwise the character returned is lowercase"a-f". The values in the range0-9 are returned as"0-9".
      Parameters:
      value - a value, only the low 4 bits0-3 of the value are used
      Returns:
      the hexadecimal character for the low 4 bits0-3 of the value
    • toHighHexDigit

      public char toHighHexDigit(int value)
      Returns the hexadecimal character for the high 4 bits of the value considering it to be a byte. If the parameterisUpperCase() istrue the character returned for values10-15 is uppercase"A-F", otherwise the character returned is lowercase"a-f". The values in the range0-9 are returned as"0-9".
      Parameters:
      value - a value, only bits4-7 of the value are used
      Returns:
      the hexadecimal character for the bits4-7 of the value
    • toHexDigits

      public <A extendsAppendable> A toHexDigits(A out, byte value)
      Appends two hexadecimal characters for the byte value to theAppendable. Each nibble (4 bits) from most significant to least significant of the value is formatted as if bytoLowHexDigit(nibble). The hexadecimal characters are appended in one or more calls to theAppendable methods. The delimiter, prefix and suffix are not used.
      Type Parameters:
      A - The type ofAppendable
      Parameters:
      out - anAppendable, non-null
      value - a byte value
      Returns:
      theAppendable
      Throws:
      UncheckedIOException - if an I/O exception occurs appending to the output
    • toHexDigits

      public String toHexDigits(byte value)
      Returns the two hexadecimal characters for thebyte value. Each nibble (4 bits) from most significant to least significant of the value is formatted as if bytoLowHexDigit(nibble). The delimiter, prefix and suffix are not used.
      Parameters:
      value - a byte value
      Returns:
      the two hexadecimal characters for the byte value
    • toHexDigits

      public String toHexDigits(char value)
      Returns the four hexadecimal characters for thechar value. Each nibble (4 bits) from most significant to least significant of the value is formatted as if bytoLowHexDigit(nibble). The delimiter, prefix and suffix are not used.
      Parameters:
      value - achar value
      Returns:
      the four hexadecimal characters for thechar value
    • toHexDigits

      public String toHexDigits(short value)
      Returns the four hexadecimal characters for theshort value. Each nibble (4 bits) from most significant to least significant of the value is formatted as if bytoLowHexDigit(nibble). The delimiter, prefix and suffix are not used.
      Parameters:
      value - ashort value
      Returns:
      the four hexadecimal characters for theshort value
    • toHexDigits

      public String toHexDigits(int value)
      Returns the eight hexadecimal characters for theint value. Each nibble (4 bits) from most significant to least significant of the value is formatted as if bytoLowHexDigit(nibble). The delimiter, prefix and suffix are not used.
      Parameters:
      value - anint value
      Returns:
      the eight hexadecimal characters for theint value
      See Also:
    • toHexDigits

      public String toHexDigits(long value)
      Returns the sixteen hexadecimal characters for thelong value. Each nibble (4 bits) from most significant to least significant of the value is formatted as if bytoLowHexDigit(nibble). The delimiter, prefix and suffix are not used.
      Parameters:
      value - along value
      Returns:
      the sixteen hexadecimal characters for thelong value
      See Also:
    • toHexDigits

      public String toHexDigits(long value, int digits)
      Returns up to sixteen hexadecimal characters for thelong value. Each nibble (4 bits) from most significant to least significant of the value is formatted as if bytoLowHexDigit(nibble). The delimiter, prefix and suffix are not used.
      Parameters:
      value - along value
      digits - the number of hexadecimal digits to return, 0 to 16
      Returns:
      the hexadecimal characters for thelong value
      Throws:
      IllegalArgumentException - ifdigits is negative or greater than 16
    • isHexDigit

      public static boolean isHexDigit(int ch)
      Returnstrue if the character is a valid hexadecimal character or codepoint. The valid hexadecimal characters are:
      • '0' ('\u0030') through'9' ('\u0039') inclusive,
      • 'A' ('\u0041') through'F' ('\u0046') inclusive, and
      • 'a' ('\u0061') through'f' ('\u0066') inclusive.
      Parameters:
      ch - a codepoint
      Returns:
      true if the character is valid a hexadecimal character, otherwisefalse
    • fromHexDigit

      public static int fromHexDigit(int ch)
      Returns the value for the hexadecimal character or codepoint. The value is:
      • (ch - '0') for'0' through'9' inclusive,
      • (ch - 'A' + 10) for'A' through'F' inclusive, and
      • (ch - 'a' + 10) for'a' through'f' inclusive.
      Parameters:
      ch - a character or codepoint
      Returns:
      the value0-15
      Throws:
      NumberFormatException - if the codepoint is not a hexadecimal character
    • fromHexDigits

      public static int fromHexDigits(CharSequence string)
      Returns theint value parsed from a string of up to eight hexadecimal characters. The hexadecimal characters are parsed from most significant to least significant usingfromHexDigit(int) to form an unsigned value. The value is zero extended to 32 bits and is returned as anint.
      API Note:
      Integer.parseInt(s, 16) andInteger.parseUnsignedInt(s, 16) are similar but allow all Unicode hexadecimal digits defined byCharacter.digit(ch, 16).HexFormat uses only hexadecimal characters"0-9","A-F" and"a-f". Signed hexadecimal strings can be parsed withInteger.parseInt(String, int).
      Parameters:
      string - a CharSequence containing up to eight hexadecimal characters
      Returns:
      the value parsed from the string
      Throws:
      IllegalArgumentException - if the string length is greater than eight (8) or if any of the characters is not a hexadecimal character
    • fromHexDigits

      public static int fromHexDigits(CharSequence string, int fromIndex, int toIndex)
      Returns theint value parsed from a string range of up to eight hexadecimal characters. The characters in the rangefromIndex totoIndex, exclusive, are parsed from most significant to least significant usingfromHexDigit(int) to form an unsigned value. The value is zero extended to 32 bits and is returned as anint.
      API Note:
      Integer.parseInt(s, 16) andInteger.parseUnsignedInt(s, 16) are similar but allow all Unicode hexadecimal digits defined byCharacter.digit(ch, 16).HexFormat uses only hexadecimal characters"0-9","A-F" and"a-f". Signed hexadecimal strings can be parsed withInteger.parseInt(String, int).
      Parameters:
      string - a CharSequence containing the characters
      fromIndex - the initial index of the range, inclusive
      toIndex - the final index of the range, exclusive.
      Returns:
      the value parsed from the string range
      Throws:
      IndexOutOfBoundsException - if the range is out of bounds for theCharSequence
      IllegalArgumentException - if length of the range is greater than eight (8) or if any of the characters is not a hexadecimal character
    • fromHexDigitsToLong

      public static long fromHexDigitsToLong(CharSequence string)
      Returns the long value parsed from a string of up to sixteen hexadecimal characters. The hexadecimal characters are parsed from most significant to least significant usingfromHexDigit(int) to form an unsigned value. The value is zero extended to 64 bits and is returned as along.
      API Note:
      Long.parseLong(s, 16) andLong.parseUnsignedLong(s, 16) are similar but allow all Unicode hexadecimal digits defined byCharacter.digit(ch, 16).HexFormat uses only hexadecimal characters"0-9","A-F" and"a-f". Signed hexadecimal strings can be parsed withLong.parseLong(String, int).
      Parameters:
      string - a CharSequence containing up to sixteen hexadecimal characters
      Returns:
      the value parsed from the string
      Throws:
      IllegalArgumentException - if the string length is greater than sixteen (16) or if any of the characters is not a hexadecimal character
    • fromHexDigitsToLong

      public static long fromHexDigitsToLong(CharSequence string, int fromIndex, int toIndex)
      Returns the long value parsed from a string range of up to sixteen hexadecimal characters. The characters in the rangefromIndex totoIndex, exclusive, are parsed from most significant to least significant usingfromHexDigit(int) to form an unsigned value. The value is zero extended to 64 bits and is returned as along.
      API Note:
      Long.parseLong(s, 16) andLong.parseUnsignedLong(s, 16) are similar but allow all Unicode hexadecimal digits defined byCharacter.digit(ch, 16).HexFormat uses only hexadecimal characters"0-9","A-F" and"a-f". Signed hexadecimal strings can be parsed withLong.parseLong(String, int).
      Parameters:
      string - a CharSequence containing the characters
      fromIndex - the initial index of the range, inclusive
      toIndex - the final index of the range, exclusive.
      Returns:
      the value parsed from the string range
      Throws:
      IndexOutOfBoundsException - if the range is out of bounds for theCharSequence
      IllegalArgumentException - if the length of the range is greater than sixteen (16) or if any of the characters is not a hexadecimal character
    • equals

      public boolean equals(Object o)
      Returnstrue if the other object is aHexFormat with the same parameters.
      Overrides:
      equals in class Object
      Parameters:
      o - an object, may be null
      Returns:
      true if the other object is aHexFormat and the parameters uppercase, delimiter, prefix, and suffix are equal; otherwisefalse
      See Also:
    • hashCode

      public int hashCode()
      Returns a hashcode for thisHexFormat.
      Overrides:
      hashCode in class Object
      Returns:
      a hashcode for thisHexFormat
      See Also:
    • toString

      public String toString()
      Returns a description of the formatter parameters for uppercase, delimiter, prefix, and suffix.
      Overrides:
      toString in class Object
      Returns:
      a description of thisHexFormat