实现说明
真正干活的是类 MacFormatter和函数 main,其余都是接线。
使用要点
- 跑完文件,输出里会留下标记——
rejected:。
常见问题
运行「HexFormat 字节十六进制互转」会打印什么?
运行文件本身,rejected: 这些前缀各对应一段演示逻辑。
核心语句
HexFormat prefixed = HexFormat.ofDelimiter(", ").withPrefix("0x").withUpperCase();
byte[] mac = {(byte) 0xde, (byte) 0xad, (byte) 0xbe, (byte) 0xef, 0x00, 0x2a};
HexFormat colonUpper = HexFormat.ofDelimiter(":").withUpperCase();
代码示例
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());
}
}
}