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> {
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16))

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();

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