Java HexFormat: แปลง byte กับ hexadecimal แบบมาตรฐานและเทสต์ round trip
ก่อน Java 17 การแปลง byte array เป็น hex มักจบที่ลูป, String.format() หรือ helper ของ dependency HexFormat ทำให้เรื่องนี้อยู่ใน standard library พร้อมตัวเลือกตัวพิมพ์ใหญ่ prefix, suffix และ delimiter
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HexFormat;
public class Main {
public static void main(String[] args) {
byte[] input = "safe".getBytes(StandardCharsets.UTF_8);
HexFormat compact = HexFormat.of();
String encoded = compact.formatHex(input);
assert encoded.equals("73616665");
assert Arrays.equals(compact.parseHex(encoded), input);
HexFormat readable = HexFormat.ofDelimiter(":").withUpperCase();
assert readable.formatHex(input).equals("73:61:66:65");
assert Arrays.equals(readable.parseHex("73:61:66:65"), input);
System.out.println("HexFormat round-trip passed");
}
}
เลือกรูปแบบตามสัญญา
compact lowercase เหมาะกับ hash และ protocol ที่ระบุรูปแบบแน่นอน ส่วน delimiter เหมาะกับ output สำหรับคนอ่าน เช่น byte dump อย่าปรับ case หรือ separator โดยเดาเมื่อระบบปลายทางมี canonical form เพราะลายเซ็นและ cache key อาจเทียบ string ตรงๆ
Hex เป็น encoding ไม่ใช่ encryption ข้อมูลลับยังอ่านย้อนกลับได้ และขนาดข้อความเพิ่มเป็นสองเท่าของจำนวน byte หาก payload ใหญ่หรือส่งผ่าน network ให้เลือก Base64 หรือ binary ตามสัญญาแทน
Recap
- กำหนด case และ delimiter ตาม contract
- เทสต์
parseHex(formatHex(bytes))แบบ round trip - อย่าสับสน hex encoding กับการปกป้องข้อมูล
- ระวังขนาดข้อความที่เพิ่มเป็นสองเท่า