Impl LowerHex For Wire Formats
Implement LowerHex and UpperHex so {:x} and {:X} render a custom struct as fixed-width hex wire fields, lowercase and uppercase.
Code
use std::fmt;
struct Packet {
kind: u8,
len: u16,
}
// LowerHex formats the wire fields in lowercase, kind 2 + len 4 digits
impl fmt::LowerHex for Packet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:02x}{:04x}", self.kind, self.len)
}
}
// UpperHex: the uppercase variant of the same wire format
impl fmt::UpperHex for Packet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:02X}{:04X}", self.kind, self.len)
}
}
fn main() {
let packet = Packet { kind: 0x1a, len: 443 };
// {:x} dispatches LowerHex; {:X} dispatches UpperHex
println!("lower: {packet:x}");
println!("upper: {packet:X}");
}What the demo formats
Packet implements both hex traits over the same wire layout: LowerHex writes kind as two lowercase digits and len as four, so {packet:x} prints 1a01bb for kind 0x1a and len 443.
UpperHex mirrors it in capitals, and the second print shows 1A01BB. Width and zero-padding live inside the impl via the {:02x}/{:04x} specs, so callers get fixed-width wire fields from either specifier without any per-call formatting.
Points worth noting
- The two traits are independent impls on the same struct.
- Zero-padding at the impl level keeps every field fixed-width.
Interactive Tools for This Topic
Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.CSS Color ConverterConvert colors between HEX, rgb(), and hsl() instantly, with support for shorthand hex and rgb or hsl inputs. Fully offline and dependency free.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.RGBA / Hex Color ConverterConvert colors between #RRGGBB, #RRGGBBAA, rgb(), and rgba() forms with alpha handling and validation.
FAQ
- Why implement both hex traits?
- Logs and wire dumps often want either case: {:x} and {:X} each dispatch to their own impl, and the demo prints both renderings of the same packet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.