Read N bytes into larger data primitive #221
-
Is it possible to easily parse a number of bytes into a larger data primitive? I'm trying to do something like so:
Then, the data I am trying to parse would have the first 3 bytes stored as |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
#[binread]
#[br(big)]
pub struct MyStruct {
#[br(reader = parse_u24)]
pub data1: u32,
pub data2: u16,
pub data3: u16,
#[br(map = |x: u8| x as i16)]
pub data4: i16,
}
/// A parser that reads a 24-bit unsigned integer into a `u32`.
#[binrw::parser(reader, endian)]
pub fn parse_u24() -> BinResult<u32> {
let mut bytes = [0; 4];
let (range, from_bytes): (_, fn(_) -> _) = match endian {
Endian::Big => (1..=3, u32::from_be_bytes),
Endian::Little => (0..=2, u32::from_le_bytes),
};
reader.read_exact(&mut bytes[range])?;
Ok(from_bytes(bytes))
} apologies if I've made any mistakes, as I'm on mobile. I have not checked the endians match what you describe. lmk if there's any issues and I'll try to correct the code accordingly |
Beta Was this translation helpful? Give feedback.
apologies if I've made any mistakes, as I'm on mobile. I have not checked the endians match wh…