0

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?

Dominik
  • 123
  • 1
  • 1
  • 6

2 Answers2

1

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()));
Schwern
  • 153,029
  • 25
  • 195
  • 336
-1
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());
}
Stargateur
  • 24,473
  • 8
  • 65
  • 91
Dominik
  • 123
  • 1
  • 1
  • 6
  • 4
    Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Dec 15 '22 at 00:59