HexFormat Byte Formatting Roundtrip
Format bytes as delimited hexadecimal and parse them back with HexFormat; uppercase, prefix, and separator are configurable and bad input fails fast.
Code
import java.util.Arrays;
import java.util.HexFormat;
public class MacFormatter {
public static void main(String[] args) {
byte[] mac = {(byte) 0xde, (byte) 0xad, (byte) 0xbe, (byte) 0xef, 0x00, 0x2a};
// 冒号分隔 + 大写:网卡 MAC 的常见形态(JDK 17+)
HexFormat colonUpper = HexFormat.ofDelimiter(":").withUpperCase();
String text = colonUpper.formatHex(mac);
System.out.println(text);
// parseHex 与 formatHex 互为逆操作,字节数组可无损往返
byte[] parsed = colonUpper.parseHex(text);
System.out.println(Arrays.equals(mac, parsed));
// 无分隔符小写:校验和、指纹的紧凑形态
System.out.println(HexFormat.of().formatHex(mac));
// 前缀 + 逗号:日志里逐字节打印
HexFormat prefixed = HexFormat.ofDelimiter(", ").withPrefix("0x").withUpperCase();
System.out.println(prefixed.formatHex(mac));
// 非法字符或奇数长度:parseHex 直接抛 IllegalArgumentException
try {
HexFormat.of().parseHex("zz");
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getClass().getSimpleName());
}
}
}How it works
HexFormat Byte Formatting Roundtrip comes down to the class MacFormatter and the function main.
Applying it
Running the file prints labeled results such as rejected: — each operation’s effect is visible in the output.
Statements that matter
HexFormat prefixed = HexFormat.ofDelimiter(", ").withPrefix("0x").withUpperCase();
byte[] mac = {(byte) 0xde, (byte) 0xad, (byte) 0xbe, (byte) 0xef, 0x00, 0x2a};
HexFormat colonUpper = HexFormat.ofDelimiter(":").withUpperCase();
Interactive Tools for This Topic
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.
FAQ
- What does HexFormat Byte Formatting Roundtrip print when run?
- No setup needed: run the file and look for labeled lines like `rejected:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.