DEV Community

Discussion on: Three bytes to an integer

lonami profile image
Lonami • Edited on

There was recently a post in URLO about this, Custom u24 type. Essentially, another option was to do the following:

u32::from_be_bytes([bytes[12], bytes[13], bytes[14], 0])

Or if you don't want to type three different indices:

let mut buffer = [0u8; 4];
wayofthepie profile image
Stephen O'Brien Author • Edited on

Wow! That's even better, didn't realize you could do that, copy_from_slice, thanks. Not sure why I didn't even think of the first one 😄

lonami profile image

After searching around in URLO, I also found this neat post on The byte order fallacy which is mildly relevant. By using from_le_bytes or from_be_bytes, we can see the byte order in a concise way and it would be trivial to change too (as opposed to bit-shifts which require a tiny bit more of work and thought).