construct-js
Advanced tools
Comparing version 0.2.2 to 0.3.0
{ | ||
"name": "construct-js", | ||
"version": "0.2.2", | ||
"version": "0.3.0", | ||
"description": "", | ||
@@ -5,0 +5,0 @@ "main": "src/index.js", |
@@ -211,7 +211,7 @@ # construct-js | ||
`BitStruct(name)` | ||
`BitStruct(name, lsbFirst = true)` | ||
Creates a BitStruct object, for storing and addressing data on the sub-byte level. | ||
Creates a BitStruct object, for storing and addressing data on the sub-byte level. If *lsbFirst* is `true`, the resulting buffer will consider the fields to be ordered from the 0th bit i.e. the first field in the BitStruct will be the least significant bit in the Buffer. If *lsbFirst* is `false`, the Buffer will contain the fields in the order they are specified. | ||
**Note**: When [bitStruct.toBuffer()](#tobuffer-1) is used, the resulting buffer will be byte aligned. This means if the size of the BitStruct is 12-bits, the resulting buffer will be 16-bits (2 bytes). | ||
**Note**: When [bitStruct.toBuffer()](#tobuffer-1) is used, the resulting buffer will be byte aligned. This means if the size of the BitStruct is 12-bits, the resulting buffer will be 16-bits (2 bytes). When *lsbFirst* is true, the most significant bits will be padded. | ||
@@ -218,0 +218,0 @@ #### flag |
@@ -302,3 +302,4 @@ class DataValue { | ||
return Array.from({length: this._size}, (_, i) => { | ||
return (this._value & 2**i) >> i | ||
const shift = this._size - (i+1) | ||
return (this._value >> shift) & 0x01 | ||
}); | ||
@@ -317,2 +318,8 @@ } | ||
class BitStruct extends Struct { | ||
constructor(name, lsbFirst = true) { | ||
super(name); | ||
this._lsbFirst = lsbFirst; | ||
} | ||
multiBit(name, size, value) { | ||
@@ -352,21 +359,18 @@ this.fields.push([name, new Bits(size, value)]); | ||
toBuffer() { | ||
return Buffer.from(this.toBytes()); | ||
} | ||
toBytes() { | ||
const bits = this.fields.reduce((bits, [_, field]) => { | ||
return [...bits, ...field.getBits()]; | ||
const fieldBits = field.getBits(); | ||
if (this._lsbFirst) fieldBits.reverse(); | ||
return [...bits, ...fieldBits]; | ||
}, []); | ||
const bytes = bits.reduce((bytes, bit, i) => { | ||
const byteIndex = Math.floor(i/8); | ||
const bitIndex = i % 8; | ||
bytes[byteIndex] += bit << bitIndex; | ||
return bytes; | ||
}, Array.from({length: this.computeBufferSize()}).fill(0)); | ||
return Buffer.from(bytes); | ||
} | ||
toBytes() { | ||
return bits.reduce((bytes, bit, i) => { | ||
const byteIndex = Math.floor(i/8); | ||
const bitIndex = i % 8; | ||
bytes[byteIndex] += bit << bitIndex; | ||
const shift = this._lsbFirst ? bitIndex : 7 - bitIndex; | ||
bytes[byteIndex] += bit << shift; | ||
return bytes; | ||
@@ -419,3 +423,3 @@ }, Array.from({length: this.computeBufferSize()}).fill(0)); | ||
Struct: (name, littleEndian = true) => new Struct(name, littleEndian), | ||
BitStruct: (name) => new BitStruct(name), | ||
BitStruct: (name, lsbFirst = true) => new BitStruct(name, lsbFirst), | ||
}; |
24149
351