0x00b0
0x00b0

Reputation: 363

How I can convert vector of hex digits into a u64?

I have byte string like this ["80", "1c", "07", "53", "1b", "fc", "c7", "01"] and I would like to convert it to long little endian, result should be something like this 128348308690640000

How would I best go about doing that?

Upvotes: 1

Views: 645

Answers (1)

Caesar
Caesar

Reputation: 8484

You'll need to combine from_str_radix and from_le_bytes. Quick example (with anyhow for error handling, you'll need to think about what you want to do if your input slice doesn't have 8 strings, or if one of them is not a hex digit.):

use anyhow::Context;

fn hex_bytes_to_u64(input: &[&str]) -> anyhow::Result<u64> {
    anyhow::ensure!(input.len() == 8, "expected 8 hex bytes");
    let bytes = input
        .iter()
        .map(|s| u8::from_str_radix(s, 16))
        .collect::<Result<Vec<_>, _>>()
        .context("Hex byte parse failure")?;
    Ok(u64::from_le_bytes(bytes.try_into().expect("u64 doesn't have 8 bytes?")))
}

Playground

Upvotes: 2

Related Questions