rust - What is the most appropriate way to convert nibbles to a u64? -
i trying learn rust , decided write program converts hex string u64.
currently, have parsed string vector of u8 values, each representing 4 bits (or "nibble"). wrote following code take vec<u8>
, return corresponding u64
. works (as far testing shows), not sure if "appropriate" way in rust go doing this.
fn convert_nibbles_to_u64(values: &vec<u8>) -> u64 { // need turn buffer u64 let mut temp:u64 = 0; in values { temp = temp << 4; unsafe { // need unsafely convert u8 u64. note // host endian-ness matter here. use std::mem; let i_64_buffer = [0u8,0u8,0u8,0u8,0u8,0u8,0u8,i.clone()]; let i_64 = mem::transmute::<[u8; 8], u64>(i_64_buffer); let i_64_be = u64::from_be(i_64); temp = temp | i_64_be; } } return temp; }
i suppose main issue don't know how else cast u8
u64
value. comment on ways improve or write code in more idiomatic, rust-like style?
edit: have tried following (unsuccessful) alternatives unsafe block:
or'ing i
u64
:
temp = temp | u64; ------ compiler error: main.rs:115:23: 115:31 error: non-scalar cast: `&u8` `u64` main.rs:115 temp = temp | u64;
or'ing i
directly:
temp = temp | i; ------ compiler error: main.rs:115:16: 115:24 error: trait `core::ops::bitor<&u8>` not implemented type `u64` [e0277] main.rs:115 temp = temp | i;
your issue simple one: for in values
, values
of type &vec<u8>
, iterates on references each value; is, i
of type &u8
. oring , adding , such references doesn’t make sense; need dereference it, getting underlying u8
. easiest way of doing writing for
loop’s pattern (for for
grammar for pattern in expression
, refer documentation on patterns more explanation if need it; simple case, for &x in y { … }
means for x in y { let x = *x; … }
):
fn convert_nibbles_to_u64(values: &[u8]) -> u64 { let mut out = 0; &i in values { out = out << 4 | u64; } out }
the whole form of loop can collapsed using iterator.fold
, too, this:
fn convert_nibbles_to_u64(values: &[u8]) -> u64 { values.iter().fold(0, |x, &i| x << 4 | u64) }
Comments
Post a Comment