Fargerik
Fargerik

Reputation: 210

How can I convert an [u8] hex ascii representation to a u64

I would like to convert my bytes array into a u64.

For example b"00" should return 0u64 b"0a" should return 10u64

I am working on blockchain, so I must find something efficient.
For example, my current function is not efficient at all.

let number_string = String::from_utf8_lossy(&my_bytes_array)
            .to_owned()
            .to_string();
let number = u64::from_str_radix(&number_string , 16).unwrap();

I have also tried

let number = u64::from_le_bytes(my_bytes_array);

But I got this error mismatched types expected array [u8; 8], found &[u8]

Upvotes: 2

Views: 720

Answers (1)

Jeff Muizelaar
Jeff Muizelaar

Reputation: 604

How about?

pub fn hex_to_u64(x: &[u8]) -> Option<u64> {
    let mut result: u64 = 0;
    for i in x {
        result *= 16;
        result += (*i as char).to_digit(16)? as u64;
    }
    Some(result)
}

Upvotes: 2

Related Questions