-
Notifications
You must be signed in to change notification settings - Fork 141
Open
Description
What is the recommended way to parse a field when a preceding field has a specific value?
For example, take this buffer:
FF 00 00 00 AA
Where FF
acts as a flag that there there is AA
Now consider this:
00 FF 00 00 BB
Having the first byte unset (but the second byte set) indicates the absence of what got assigned AA before. Instead BB means something different here.
If both are set:
FF FF 00 00 AA BB
The fields corresponding to AA and BB will be assigned.
Parsing pseudocode:
const buffer = Buffer.from("FF000000AA", "hex");
const hasFieldA = buffer[0] === 0xff;
const hasFieldB = buffer[1] === 0xff;
const result = {
a: null,
b: null,
};
let index = 5;
if (hasA) {
result.a = buffer[index++];
}
if (hasB) {
result.b = buffer[index++];
}
I have some hardware that uses this kind of format (it uses bit flags though).
Is something like this possible?
Edit:
I came up with this:
const Parser = require("binary-parser").Parser;
const parser = new Parser()
.uint8("hasA")
.uint8("hasB")
.uint8("hasC")
.uint8("hasD")
.choice({
tag: "hasA",
defaultChoice: new Parser(),
choices: {
0xff: new Parser().uint8("a"),
}
})
.choice({
tag: "hasB",
defaultChoice: new Parser(),
choices: {
0xff: new Parser().uint8("b"),
}
});
console.log(parser.parse(Buffer.from("FFFF0000AACC", "hex")));
Is this the recommeded way or is there something simpler?
Metadata
Metadata
Assignees
Labels
No labels