I am working on parsing some binary files, I have them opened and in an ArrayBuffer
.
In the particular file structure I am reading, there are a number of bits which are boolean
and I can check whether they are checked with:
(flag & 1) != 0; // bit 0
(flag & 2) != 0; // bit 1
(flag & 4) != 0; // bit 2
etc.
However, I am having trouble getting the values of the bits followed. They span over multiple bits (for example bits 4-6) and consist of an integer value from 0-7.
How are multiple bits read like that? I understand that this isn't as much of a JavaScript question than that of how bits and bitwise operators work.
Assuming you want 4-6 bits from a byte like this:
76543210
^^^
You would construct a bit mask like this:
0x70
which means:
01110000
And then you would & that with the number and shift to right 4 times:
( byte & 0x70 ) >> 4
//Number between 0-7