keichi / binary-parser

A blazing-fast declarative parser builder for binary data
MIT License
864 stars 134 forks source link

[Question] How to read a 33 bits field? #207

Closed enricovittorini closed 2 years ago

enricovittorini commented 2 years ago

Hello all, Can someone guide me on how to read 33 bits? The bitX() is limited to 32 Thanks!

enricovittorini commented 2 years ago

can someone help?

enricovittorini commented 2 years ago

hi! is this a live project?

keichi commented 2 years ago

Apologies, I missed this one. Currently, there are no built-in methods to read a 33-bit field. A workaround would be to combine a 32-bit field and a 1-bit field manually.

enricovittorini commented 2 years ago

Thanks @keichi would you show me an example how to do it? Thanks

keichi commented 2 years ago

Here's an example:

const Parser = require("binary-parser").Parser;

const parser = new Parser()
    .bit32("a")
    .bit1("b");

const buf = Buffer.from("aaaaaaaa80", "hex");
const res = parser.parse(buf)

console.log((BigInt(res.a) << BigInt(1) | BigInt(res.b)).toString(16)); // -> 155555555

Note that you need to use BigInt since bitwise operations on Number automatically convert the operands and results to 32-bit integers.

keichi commented 2 years ago

I will close this issue for now. Please reopen if needed.