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.

RustData Integrity

Code

rustsnippet
35 lines
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

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:`.