3

I've read a file into vector of unsigned bytes:

let data = fs::read("test.bin").expect("Unable to read file");

How can I convert/cast this vector to a Vec<u64>, with every eight bytes constituting a u64?

The "duplicates" do not provide a solution, but I found it in the meanwhile:

let vec8: Vec<u8> = vec![1,2,3,4,5,6,7,8];
let mut vec64: Vec<u64> = vec![0;vec8.len()/8];
BigEndian::read_u64_into(&data, &mut vec64);
2080
  • 1,223
  • 1
  • 14
  • 37
  • 2
    Is one u64 supposed to be built from one u8 or from 4 of them ? What's the goal ? – Denys Séguret Jul 10 '19 at 14:49
  • It's a bit strange to convert four `u8` to a `u64`, you would normally need 8. – starblue Jul 10 '19 at 18:17
  • @starblue Thank you, corrected! – 2080 Jul 10 '19 at 21:23
  • 1
    Converting a `Vec` to a `Vec` inplace is not safe, and you should never try it. You will have to make a copy. The only way to avoid it is to allocate a `Vec` directly and write bytes into it (because a conversion from `&mut [u64]` to `&mut [u8]` can be safe). See also the [`safe-transmute`](https://docs.rs/safe-transmute/0.11.0-rc.2/safe_transmute/) crate. – E_net4 Jul 11 '19 at 09:02
  • @E_net4theClose-voter Like the solution I indicated? – 2080 Jul 11 '19 at 11:29
  • Yes, unless you can also avoid making the `Vec` in the first place. – E_net4 Jul 11 '19 at 11:30
  • I will not say it is strange to map a vector of u8 to one in u64. Assume we have a continues stripe of memory (array of u8 or so) this could be a string/str seeing as bytes. But what if you would like to see this as an array of u16, u32 or u64 instead? F.x. if we need to check for some abstraction of the string that fill more than a byte but always hold another size. it could be a data stream which we need to check for some format, where it would be more efficient to check against u16 or another size parameter. i.e comparison of one u16 will faster than two comparisons of one byte each. – kam Sep 17 '20 at 19:02
  • 3
    **Not a duplicate as increasing the size of a vector is not the same as decreasing it and a `vec<>`isn t an array.** – user2284570 Dec 27 '20 at 11:29

0 Answers0