In a previous article, we covered the basics of what binary is and how we count in it. In this article, we’re going to look at how we can use binary to represent and manipulate data in a more efficient way using bitmasking. This technique is widely used in game development for tasks like collision detection, state management, and more.

What is Bitmasking?

Bitmasking is a technique where we use individual bits in a number to represent separate boolean (true or false) flags. This technique is so powerful for two main reasons:

  • Memory efficiency: Instead of using multiple variables to represent different states, we can pack them into a single number.
  • Performance: Bitwise operations are extremely fast, allowing us to check and manipulate multiple flags in a single operation1.

We can demonstrate the power of bitmasking with a simple example. Let’s say we have a game character with several boolean flags that represent different states2:

var is_player := true
var is_enemy := false
var can_jump := true
var is_invincible := false
var has_key := true
var is_poisoned := false
var is_stunned := false
var is_invisible := true

We can pack all of these into a single number where each bit represents one of these states:

# Each bit represents a different state
# 10101001 in binary = 169 in decimal
var player_flags := 0b10101001
8 different booleans packed into a single byte

In this example, we see each of our 8 boolean flags packed into a single byte.

It gets crazier the deeper you go

In languages like C, C++, Rust, and Go (to name a few), if we modeled our character using a struct, then having separate boolean variables wouldn’t take up 8 bits — it would take 8 bytes!

This is because most languages will align the data in memory to the size of the largest type. So if we had 8 booleans, they would take up 8 bytes (64 bits) instead of 1 byte (8 bits). This is where bitmasking really shines and helps us save memory.

Our first bitwise operator: &

With an idea of how we might pack our booleans into a single number, let’s look at how we can manipulate them. The first operator is we’ll look at is the AND operator or &. This is used in a binary operation to compare two numbers bit by bit. The result is a new number where each bit is set to 1 only if both bits in the original numbers are also 1.

AND operation on two binary numbers