Selective Exposure: Bitmasking as Pattern Protection
In shibori, you bind sections of fabric before dyeing—the tied areas resist the dye, creating patterns where protection meets exposure. Bitmasking works identically: you apply a binary pattern to selectively protect or expose bits during an operation.
The core technique uses AND, OR, and XOR with a mask value. Want to extract the lower four bits of a byte? AND it with 0x0F (binary 00001111)—the zeros block everything above, the ones let the lower bits through:
value = 0xA7 # 10100111
mask = 0x0F # 00001111
IO.puts("Extracted: #{Integer.to_string(Bitwise.band(value, mask), 2)}") # 0111
# Setting specific bits: OR with 1s where you want them
flags = 0b0000
set_bits = Bitwise.bor(flags, 0b0101)
IO.inspect(set_bits, base: :binary) # 0101
# Toggling bits: XOR flips matching positions
toggled = Bitwise.bxor(set_bits, 0b0011)
IO.inspect(toggled, base: :binary) # 0110
Bash inherited bitwise operators from C, making them available for shell arithmetic:
#!/bin/bash
perms=0644 # rw-r--r--
# Extract owner permissions (first 3 bits from right, shifted)
owner=$((perms >> 6 & 0x7))
echo "Owner can: $owner" # 6 = rw-
# Check if group has write permission (bit 4)
if (( (perms >> 3 & 0x2) == 0 )); then
echo "Group cannot write"
fi
The analogy holds: tie specific positions, apply the operation (dye/boolean), untie to reveal the pattern. Every network packet filter, every permission check, every graphics alpha channel uses this—binary patterns as resist.