Home > Enterprise >  Getting [u64; 8] for [u8; 32] in Rust
Getting [u64; 8] for [u8; 32] in Rust

Time:12-15

I need a little code snippet and maybe if someone has time an explanation.

I have a hash function that I use using two different programming languages. The results are then compared in Rust.

What I want to get back is [3246643754, 1918081665, 2401493466, 600956609, 3662614728, 2858571937, 2319608302, 3673956376] so a vector of 8 u64 numbers. This is what the first usage of the hash function returns (I assume it is correct).

The same hash functions returns - used on a different part in the code -

[42, 218, 131, 193, 129, 154, 83, 114, 218, 225, 35, 143, 193, 222, 209, 35, 200, 16, 79, 218, 161, 88, 98, 170, 238, 105, 66, 138, 24, 32, 252, 218]

so an array of 32 numbers u8.

How can I now convert the latter into the former to compare them?

CodePudding user response:

It looks like you're casting network order u8s to u32 and then storing them as u64.

You can convert each slice of 4 u8s to u32 using u32::from_ne_bytes, then cast to u64.

let num: u64 = u64::from(u32::from_ne_bytes(input[0..4].try_into().unwrap()));

CodePudding user response:

let mut h_output = Vec::<u64>::new();

for i in 0..=7 {
    let bytes = u32::from_ne_bytes(output[i*4..i*4 4].try_into().unwrap());
    h_output.push(bytes.into());
}
  • Related