liveBook · Manning

Bit mask

As explained in Clojure: The Essential Reference

A bit mask is a bit pattern whose positions selectively test, set, clear, or flip corresponding bits in another pattern.

A bit mask is a deliberately constructed bit pattern used with bitwise operations to inspect or modify selected positions in another pattern. With bit-and, 1s preserve corresponding bits and 0s hide them. section 3.2.3

Use the mask according to the desired bit operation:

  • Flip positions with bit-xor and a mask containing 1s at those positions; compare bit sets by checking whether xor produces only 0s. section 3.2.3

Inspect and clear the fourth bit

Define the fourth-bit mask as 2r00001000. Applying (bit-and 2r11001001 fourth-bit-set-mask) yields "00001000", confirming that the position is set. Applying (bit-clear 2r11001001 3) yields "11000001", clearing that position without explicitly supplying an inverted mask.

How Clojure: The Essential Reference covers it

How deep it goes
Explains construction and application for testing, clearing, flipping, and comparing bits, without developing a broader abstraction.
Examples
Demonstrates binary masks for selecting the fourth bit, clearing it, testing it, flipping bits, and comparing bit sets.
What it assumes
Assumes binary bit patterns and boolean operations, while establishing the masking behavior through Clojure examples.
What you can do after
Apply it via Clojure's bitwise functions to inspect or modify selected positions in integer bit patterns.
How it connects
Connects bit-and, bit-test, bit-clear, bit-xor, bit-set, bit-flip, and bitwise operations.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.