Read a u16 from one or 2 bytes #242
Unanswered
lvauvillier
asked this question in
Q&A
Replies: 1 comment 2 replies
-
I finally got it to work with a custom parser, but I'm wondering if there is a solution using built-in directives. #[binrw::parser(reader)]
pub fn parse_record_length(two_bytes: bool) -> BinResult<u16> {
let mut bytes = [0; 2];
reader.read_exact(&mut bytes[if two_bytes { 0..=1 } else { 0..=0 }])?;
Ok(u16::from_le_bytes(bytes))
} and #[binread]
#[derive(Debug)]
#[br(little)]
#[br(import(format_version: u8))]
struct RecordFrame {
record_type: u8,
#[br(args(format_version > 12), parse_with = parse_record_length)]
length: u16,
#[br(count = length)]
data: Vec<u8>,
end: u8,
} |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi ,
I'm trying to parse a file that have an integer field encoded as u8 for old formats and u16 for new formats.
How to achieve this ?
Beta Was this translation helpful? Give feedback.
All reactions