keichi / binary-parser

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

Array with non 8bit alignment #244

Open xvaara opened 10 months ago

xvaara commented 10 months ago

Is it possible to have an array that isn't aligned to 8bits?

https://stackblitz.com/edit/stackblitz-starters-cxezrc?file=index.js

nick-hunter commented 10 months ago

I don't think this is currently possible with an array. I would recommend using the getCode() method to understand why. For your example, each loop iteration is reading in 24 bits. $tmp2 = (dataView.getUint16(offset) << 8) | dataView.getUint8(offset + 2);. Any leftover bits will be dropped.

There is a hacky way to accomplish this, but you can't use the Array type. This may or may not make sense for your application. I would make sure the array as a whole is a multiple of 8 bits. Also be careful with nested bit fields. There are some issues if you have a nest inside a nest.

// 22    22    22...
// 10110 10110 10110 10110 10110 10110 00
const test = Buffer.from("B5AD6B58", "hex");

const p = new Parser();
for(let i = 0; i < 3; i++){
    p['bit5'](`a${i}`);
    p['bit5'](`b${i}`);
}

console.log(p.parse(test)) // { a0: 22, b0: 22, a1: 22, b1: 22, a2: 22, b2: 22 }

Hope this helps!