Set Operations with Bitsets

Once each element has a stable bit position, bitwise operations can compute union, intersection, and membership changes directly.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Use a four-element universe
  2. Preserve the universe
  3. Map bit positions consistently before combining
  4. Keep unused positions outside the semantic universe

Use a four-element universe

If A holds positions zero and two, it is 0101. If B holds positions one and two, it is 0110. Their bitwise OR gives 0111 and AND gives 0100. These match set union and intersection.

Preserve the universe

If two bitsets use different label-to-position mappings, combining the words has no shared membership interpretation. Use the same position keys before applying an operation.[1]

Map bit positions consistently before combining

With one bit per label A through E from right to left, 10101 represents A, C and E. The mask 01110 represents B, C and D. Their OR represents all five labels and their AND represents C alone. See power sets as bit patterns.

X              10101
Y              01110
X OR Y         11111
X AND Y        00100
X AND NOT Y    10001 within width five

Keep unused positions outside the semantic universe

When the logical universe is smaller than the storage word, mask complement results to the allowed positions. If two bitsets were built using different label orders, convert them first. Test empty, fully occupied and disjoint sets.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩