Hex Encode Bytes With Format Specifiers
Render byte slices as lowercase and uppercase hex using {:02x} and {:02X}, then re-parse the string back into bytes.
Code
fn to_hex(bytes: &[u8], upper: bool) -> String {
bytes
.iter()
.map(|b| {
// {:02x} 两位小写十六进制,不足补零;X 为大写
if upper {
format!("{b:02X}")
} else {
format!("{b:02x}")
}
})
.collect()
}
fn from_hex(s: &str) -> Option<Vec<u8>> {
if s.len() % 2 != 0 {
return None;
}
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok())
.collect()
}
fn main() {
let bytes = [0x0a, 0xff, 0x42];
let lower = to_hex(&bytes, false);
let upper = to_hex(&bytes, true);
println!("lower: {lower}");
println!("upper: {upper}");
let roundtrip = from_hex(&lower).expect("valid hex");
println!("roundtrip ok: {}", roundtrip == bytes);
println!("odd length rejected: {}", from_hex("abc").is_none());
}What the code does
The code’s whole job belongs to the functions to_hex, from_hex and main.
Caveats
- No external surface: all behavior comes from the standard library.
Using it
The primary signature is fn to_hex(bytes: &[u8], upper: bool) -> String
Output lines are prefixed (lower:, upper:, roundtrip ok:), making each step’s effect easy to spot.
There are 2 calls inside main — to_hex and from_hex — executed top to bottom.
Key statements
fn from_hex(s: &str) -> Option<Vec<u8>> {
if s.len() % 2 != 0 {
return None;
}
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok())
.collect()
}
Interactive Tools for This Topic
Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.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.
FAQ
- What does Hex Encode Bytes With Format Specifiers print when run?
- Running the file directly is enough — expect labeled output lines such as `lower:`, `upper:`, `roundtrip ok:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.