实现说明
活动部件是函数 to_hex、from_hex、main。
使用要点
- 演示输出是带标签的(
lower:、upper:、roundtrip ok:),每个操作都会留下自己的一行标注。 - 运行整个文件:
main会依次驱动to_hex、from_hex。
常见问题
运行「用格式说明符编码十六进制」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 lower:、upper:、roundtrip ok: 标签标明各步骤。
主签名形如 fn to_hex(bytes: &[u8], upper: bool) -> String
核心语句
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 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());
}