Bitwise Operations & Bit Sets
🎛️ Bitwise Operations, Bitfields & Bit Sets in Odin
Bitwise operations allow packed storage of binary game state (flags, collision masks, input buttons, inventory states) in minimal memory. Odin replaces error-prone C macro bitmasks with first-class bit_set types.
🧱 1. Type-Safe bit_set vs. Raw Bitmasks
In C/C++, flags use raw integer masks (flags |= (1 << 3)). In Odin, bit_set builds a strongly typed bitfield on top of an enum:
package main
import "core:fmt"
Player_State :: enum {
Grounded,
Crouching,
Sprint_Active,
Poisoned,
Invulnerable,
}
// 1 byte backing integer storing up to 8 distinct boolean flags
Player_Flags :: bit_set[Player_State; u8]
main :: proc() {
flags: Player_Flags = {.Grounded, .Sprint_Active}
// Adding a flag
flags |= {.Invulnerable}
// Removing a flag
flags -= {.Sprint_Active}
// Checking membership
if .Grounded in flags {
fmt.println("Player is on the floor!")
}
}
⚡ 2. Raw Bitwise Operators
| Operator | Operation | Example | Result (u8) |
|---|---|---|---|
& | Bitwise AND | 0b1100 & 0b1010 | 0b1000 |
| | Bitwise OR | 0b1100 | 0b0011 | 0b1111 |
~ | Bitwise XOR | 0b1100 ~ 0b1010 | 0b0110 |
&~ | Bit Clear (AND NOT) | 0b1100 &~ 0b1000 | 0b0100 |
<< | Left Shift | 0b0001 << 3 | 0b1000 (8) |
>> | Right Shift | 0b1000 >> 2 | 0b0010 (2) |
🔗 Related Notes
- Types — Sized types, struct alignment (
#align), and tagged unions. - Network Serialization & Delta Compression — Bit-packing and network change masks.
- Variables — Constants and compile-time evaluations.
- Odin Programming Language Index — Language overview.