Datastructures: bitmasks
From wikinotes
Bitmasks are an efficient way of combining boolean options that can be combined together.
The most familiar usage is probably unix filesystem permissions.
Under the hood
A bitmask is simply a combination of binary numbers into an integer.
Reusing unix permissions, say we have 3x combinable options.
- readable
- writable
- executable
# base(2) -- base(10) # (rwx) 001 # 1 010 # 2 011 # 3 100 # 4 101 # 5 110 # 6 111 # 7
Usage
Bitwise operators allow you to assign/unassign a flag for each digit of the binary number.
|
sets(1) the bit at that position^
unsets(0) the bit at that positionreadable = 5 # binary: 100 writable = 2 # binary: 010 executable = 1 # binary: 001 readable(100) | executable(001) # 5(101) readable(100) | writable(010) # 6(110) readable(100) | writable(010) | executable(001) # 7(111) (readable(100) | writable(010) | executable(001)) ^ executable(001) # 6(110)