How can I convert a hex string to a u8 slice?

You can also implement hex encoding and decoding yourself, in case you want to avoid the dependency on the hex crate:

use std::{fmt::Write, num::ParseIntError};

pub fn decode_hex(s: &str) -> Result<Vec<u8>, ParseIntError> {
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16))
        .collect()
}

pub fn encode_hex(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for &b in bytes {
        write!(&mut s, "{:02x}", b).unwrap();
    }
    s
}

Note that the decode_hex() function panics if the string length is odd. I’ve made a version with better error handling and an optimised encoder available on the playground.

Leave a Comment