If you work for an organization that deals with millions/billions of transactions, you definitely need this. Bit-Packing is the technique of cramming multiple logical values, booleans/flags – small integers, into a single primitive type by manipulating individual bits.
The Problem
Let’s say you want to store 8 different flags, like:
- IsAdmin
- IsVerified
- HasSubscription
- IsOnTrial
- IsBanned
- IsDeleted
- IsEmailConfirmed
- IsPhoneConfirmed
If you store them as 8 separate bool values, that’s 8 bytes (1 byte per bool), even though each of these is just a 1 or 0.
But… a single byte (which is 8 bits) can already hold 8 true/false values!
The Idea Behind Bit-Packing
Each bit in a byte can represent one flag. Like this:
Bit positions: 7 6 5 4 3 2 1 0
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
Example: 1 0 1 1 0 0 0 1
Each 1 or 0 is a boolean value. We just need to get/set the right bit.
Code Example
Let’s create a simple example using a byte to store multiple flags:
[Flags]
public enum UserFlags : byte
{
IsAdmin = 1 << 0,
IsVerified = 1 << 1,
HasSubscription = 1 << 2,
IsOnTrial = 1 << 3,
IsBanned = 1 << 4,
IsDeleted = 1 << 5,
IsEmailConfirmed = 1 << 6,
IsPhoneConfirmed = 1 << 7
}
Here’s how we’d use them:
UserFlags flags = 0;
// Set flags
flags |= UserFlags.IsAdmin;
flags |= UserFlags.IsVerified;
// Check if IsAdmin is set
bool isAdmin = (flags & UserFlags.IsAdmin) != 0;
Console.WriteLine(isAdmin);
// Unset a flag
flags &= ~UserFlags.IsAdmin;
Console.WriteLine(isAdmin);
Let’s explain what happened.
flags |= IsAdmin;→ sets the bit (turns it to 1)flags & IsAdmin→ checks if the bit is onflags &= ~IsAdmin→ unsets the bit (turns it to 0)
Each operation is super fast and only uses a single byte of memory!
Why Use Bit-Packing?
- Saves memory: Instead of 8
boolvalues (8 bytes), you just use 1 byte. - Compact storage: Great for performance-critical code or serializing data.
- Fun: Honestly, it’s kinda fun to do once you understand it
When Not to Use It
Bit-packing is neat, but don’t overuse it. If readability or maintainability suffers, or if you only have 2-3 booleans, stick to regular properties.
But if you’re packing a lot of flags — say for game entities, network messages, or configuration settings — it’s a great trick to know.
Final Thoughts
Bit-packing might sound like a low-level optimization, but it’s a useful tool for any C# developer. It’s also a great way to understand how data is actually stored in memory.
Next time you find yourself managing a bunch of flags — consider packing them up. Literally.
Affiliate promo
If you love learning new stuff and want to support me, consider buying a course from Dometrain using this link: Browse courses – Dometrain. Thank you!
Leave a comment