mirror of
https://github.com/gchq/CyberChef.git
synced 2025-05-10 08:15:00 -04:00
Added the ability to specify leftMostBitFirst
This commit is contained in:
parent
54286784a7
commit
3ebec7117b
1 changed files with 42 additions and 19 deletions
|
@ -93,17 +93,40 @@ export default class Stream {
|
|||
/**
|
||||
* Reads a number of bits from the buffer.
|
||||
*
|
||||
* @TODO Add endianness
|
||||
*
|
||||
* @param {number} numBits
|
||||
* @param {bool} [leftMostBitFirst=false]
|
||||
* @returns {number}
|
||||
*/
|
||||
readBits(numBits) {
|
||||
readBits(numBits, leftMostBitFirst=false) {
|
||||
if (this.position > this.length) return undefined;
|
||||
|
||||
let bitBuf = 0,
|
||||
bitBufLen = 0;
|
||||
|
||||
if (leftMostBitFirst) {
|
||||
// Add remaining bits from current byte
|
||||
const mask = ((1 << (8 - this.bitPos)) -1);
|
||||
bitBuf = this.bytes[this.position++] & mask;
|
||||
bitBufLen = 8 - this.bitPos;
|
||||
this.bitPos = 0;
|
||||
|
||||
// Not enough bits yet
|
||||
while (bitBufLen < numBits) {
|
||||
bitBuf = (bitBuf << 8) | this.bytes[this.position++];
|
||||
bitBufLen += 8;
|
||||
}
|
||||
|
||||
// Reverse back to numBits
|
||||
const excess = bitBufLen - numBits;
|
||||
bitBuf = bitBuf >> excess;
|
||||
bitBufLen -= excess;
|
||||
this.position--;
|
||||
this.bitPos = 8 - excess;
|
||||
|
||||
return bitBuf;
|
||||
|
||||
} else {
|
||||
|
||||
// Add remaining bits from current byte
|
||||
bitBuf = (this.bytes[this.position++] & bitMask(this.bitPos)) >>> this.bitPos;
|
||||
bitBufLen = 8 - this.bitPos;
|
||||
|
@ -125,7 +148,7 @@ export default class Stream {
|
|||
}
|
||||
|
||||
return bitBuf;
|
||||
|
||||
}
|
||||
/**
|
||||
* Calculates the bit mask based on the current bit position.
|
||||
*
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue