Bit fields to optimize comparison of multi state data

suggest change

A bit field stores several boolean states in the bits of one number. A set bit represents true, and a clear bit represents false. Bit fields used to be routine because they saved memory. They are less important for that reason now, but they still simplify some tests.

For example, keyboard input. The direction keys—up, down, left, and right—can be encoded in one number, one bit each. keyCode is deprecated; the numeric values below are what this example depends on. In a browser:

Example reading keyboard via bitfield

let bitField = 0;  // the value to hold the bits
const KEY_BITS = [4,1,8,2]; // left up right down
const KEY_MASKS = [0b1011,0b1110,0b0111,0b1101]; // left up right down
window.onkeydown = window.onkeyup = function (e) {
    if(e.keyCode >= 37 && e.keyCode <41){
        if(e.type === "keydown"){
            bitField |= KEY_BITS[e.keyCode - 37];
        }else{
            bitField &= KEY_MASKS[e.keyCode - 37];
        }
    }
}

Example reading as an array

const directionState = [false,false,false,false];
window.onkeydown = window.onkeyup = function (e) {
    if (e.keyCode >= 37 && e.keyCode <41){
        directionState[e.keyCode - 37] = e.type === "keydown";
    }
}

To turn a bit on, use bitwise OR (|) with the value of that bit. bitField |= 0b10 sets the second bit. To turn a bit off, use bitwise AND (&) with a mask that has every bit set except that one. With four bits, bitField &= 0b1101 clears the second bit.

The bit-field update is a little harder to write than storing each key in an array. The payoff is the tests.

To test that every key is up:

// bit field: every bit is clear
if (!bitField) {
  // no keys are down
}

// array: every entry is false (OR, not AND)
if (!(directionState[0] || directionState[1] || directionState[2] || directionState[3])) {
  // no keys are down
}

You can set some constants to make things easier

// postfix U,D,L,R for Up down left right
const KEY_U = 1;
const KEY_D = 2;
const KEY_L = 4;
const KEY_R = 8;
const KEY_UL = KEY_U + KEY_L; // up left
const KEY_UR = KEY_U + KEY_R; // up Right
const KEY_DL = KEY_D + KEY_L; // down left
const KEY_DR = KEY_D + KEY_R; // down right

You can then quickly test for many various keyboard states

if ((bitField & KEY_UL) === KEY_UL) { // up and left are both down; other keys may be too
}
if (bitField & KEY_UL) {              // up, left, or both are down
}
if (bitField & KEY_U) {               // up is down; other keys may be too
}
if (!(bitField & KEY_U)) {            // up is up; other keys may be down
}
if (!bitField) {                      // no keys are down
}
if (bitField) {                       // at least one key is down
}

For a single bit, (bitField & KEY_U) === KEY_U is the same test as bitField & KEY_U. The === form matters when the mask covers more than one bit, as with KEY_UL.

The keyboard input is just one example. Bitfields are useful when you have various states that must in combination be acted on. JavaScript can use up to 32 bits for a bit field. Using them can offer significant performance increases. They are worth being familiar with.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents