Set Flags shows how to store multiple boolean flags in a single integer value. In programming, this is known as a bitmask or as bit flags, and the idea is based on the binary number system where each digit can be only 0 or 1 (on or off, true or false).

For example, in the binary number 1010, you have four bit flags: flags 0 and 3 are false, and flags 1 and 4 are true. The decimal equivalent of 1010 is 10 (21 + 23).

Binary Decimal Power of 2
00000001 1 20
00000010 2 21
00000100 4 22
00001000 8 23
00010000 16 24
00100000 32 25
01000000 64 26
10000000 128 27

9 thoughts on “Set Flags and bitmasks”

• Thanks for the link. This Set Flags post was something that’s been sitting in my Drafts folder for years, and I finally got around to posting it.

1. thanks for this explanation ! but i don’t understand your example about the binary number “1010”. You’re talking about four bit flags from 0 to 4, that’s five? no ? but i’m not a coding expert, so i’m perhaps totally wrong there ?

• 1010 is actually 8, not 6. Thanks for pointing out that error. I corrected my post.

0000 is a four-digit number, so there are only four bits that can be set, so we say there are four flags. You can have many (16) combinations of flags, but there only four individual flags.

• Actually the answer is ten (8×1 + 4×0 + 2×1 + 1×0)

• Oh my. thx

• Heh, no, it’s just that Monday was a holiday (Labor Day) and I was lazy.