DEV Community

Discussion on: Three bytes to an integer

Collapse
 
lonami profile image
Lonami • Edited

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];
buffer[..3].copy_from_slice(&bytes[12..15])
u32::from_be_bytes(buffer)
Collapse
 
wayofthepie profile image
wayofthepie • Edited

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 😄

Collapse
 
lonami profile image
Lonami

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).