Way to extract data from a raw byte vector

Is there a better way to extract data from a byte vector than this?

fn get_data_from_byte_vector(index: usize, byte_vector: Vec<u8>) -> usize {
    let mut data: usize = 0;
    for offset in 0..std::mem::size_of::<usize>() {
        data += (byte_vector[index + offset] as usize) << (offset * 8);
    }
    data
}

fn main() {
    println!("{}", get_data_from_byte_vector(2, vec![2, 34, 8, 1, 0, 3, 0, 0, 0, 0, 0, 0]));
}

Better in what way?

Is get_data_from_byte_vector meant to extract a single bit with each iteration?

single bit with each iteration?

No, single byte.

Better in what way?

And better in the sense of cleaner. Not messy.

The code doesn't make sense. You can't cast (as) to an arbitrary, unknown type. You can't perform random >> and + operations on an arbitrary, unknown type. You can't return a usize as an arbitrary, unknown type.

If the actual XY goal is to go from size_of::<T> bytes to a T, there's no sound way to do that for an arbitrary T either.

If that's not your goal, you're going to have to explain more.

2 Likes

I tried to make my question too generic. I have edited the question.

To get a little-endian usize from a slice of bytes starting at a certain index, you can use usize::from_le_bytes(byte_vector[index..index + size_of::<usize>()].try_into().unwrap()). If you need to break up the entire slice into usizes, you could write byte_vector.chunks_exact(size_of::<usize>()).map(|chunk| usize::from_le_bytes(chunk.try_into().unwrap())), which produces an iterator of usizes.

6 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.