Skip to content

Read N bytes into larger data primitive #221

Answered by jam1garner
ARizzo35 asked this question in Q&A
Discussion options

You must be logged in to vote
#[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 wh…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@octylFractal
Comment options

Answer selected by ARizzo35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants