For example, an individual byte is converted to a string of hexadecimal digits using toHexDigits(int)
and converted from a string to a primitive value using fromHexDigits(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 the HexFormat
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 the HexFormat
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 a value-based class; use of identity-sensitive operations (including reference equality (==
), identity hash code, or synchronization) on instances of HexFormat
may have unpredictable results and should be avoided. The equals
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 a NullPointerException
to be thrown.