Home
Blog
Using Single Bits for Bools
Updated
Dot Net Perls

Using Single Bits for Bools

Suppose you have a class (or struct, depending on your language of choice) that has a bool field. This bool indicates something important or is some kind of flag. Each class instance can be accessed as an element of an array, so it has an index.

It seems at first that each class instance must use one byte for the bool field. But there is another way—not necessarily better, but more memory-efficient: we can use another array to store each flag as a single bit.

Each byte has 8 bits, so if we want to access the appropriate byte in the array for a class in our program, we can just its index and divide it by 8. Then a modulo division will give us the exact bit position in that byte.

Is this approach of using separate arrays to minimize memory usage (also called data-oriented programming, or arena allocation) always better? No, it is not—it reduces memory locality in some cases, and causes extra instructions to be executed to address the byte array. But if you have many objects you are dealing with, consider using single bits to represent bools.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
An RSS feed is available for this blog.
Home
Changes
© 2007-2025 Sam Allen