One integer can store several on/off values. Give each value its own bit, then read or change that bit with a bitwise operation. A bit used this way is called a flag.
The weather problem#
What’s the weather like where you are? It might be sunny, cloudy, rainy, or snowy. You might be in a downpour with snow mixed in. It can even rain while the sun is out. A program that records the weather needs to handle combinations like sun and rain or wind and rain.
Using Boolean values#
A Boolean has two possible values. We can represent true with 1 and false with 0, just as a digital signal can use high and low levels to represent the two states. In a C condition, zero counts as false and any nonzero value counts as true.
Start with just two weather conditions, sun and rain. If it’s sunny and there’s no rain, set sun to 1 and rain to 0.
int sun = 1;
int rain = 0;We can use those values in two if statements. Since sun is 1, the first statement prints “Sunny.” Since rain is 0, the second skips its print statement.
if (sun)
{
printf("Sunny\n"); // Runs because sun is true (1).
}
if (rain)
{
printf("Rain\n"); // Skipped because rain is false (0).
}Now suppose it’s raining and snowing, with wind, thunder, and lightning. With a separate variable for each condition, the same pattern grows to six variables.
int sun = 0;
int rain = 1;
int snow = 1;
int wind = 1;
int thunder = 1;
int lightning = 1;Each new condition takes another variable, and you have to carry those variables everywhere you need the full weather reading. Could we store one condition or a whole combination in a single variable?
Using bitwise flags#
Bitwise flags pack Boolean values into the bits of an integer. Each bit holds a 0 or a 1, and bitwise operations let us work with those values in place.
Counting in binary#
If you already know binary, skip to the next section.
In decimal, count from 0 to 9 and then carry into the tens place to write 10. Count from 10 to 19 and carry again to write 20. Once both places reach 9, the next carry gives 100.
Digital circuits use logic gates that work with two signal levels, represented as 0 and 1. Binary uses those same two digits. In base two, you carry after 1, so decimal 2 is written as 10. The table shows the first five numbers with four bits each.
| 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| 0000 | 0001 | 0010 | 0011 | 0100 |
Decimal 0 and 1 use the same digits in binary. Counting one past 0001 gives 0010. Keep applying the rule and you can write 5 through 9 the same way. The carry from 0111 to 1000 works like the carry from 99 to 100 in decimal.
| 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|
| 0101 | 0110 | 0111 | 1000 | 1001 |
AND, OR, and XOR#
If you already know how AND, OR, and XOR work, skip to the next section.
C uses & for bitwise AND, | for bitwise OR, and ^ for bitwise exclusive OR (XOR). Each operator works on matching pairs of bits. For a single pair of bits, the rules are the same as for logical conjunction (AND), disjunction (OR), and exclusive disjunction (XOR). Their mathematical symbols are shown below.
In LaTeX, the commands for these symbols are \land, \lor, and \oplus. In Typst math mode, use and, or, and xor.
AND gives 0 if either bit is 0. It gives 1 only when both bits are 1.
| A | B | Result |
|---|---|---|
| True / 1 | True / 1 | True / 1 |
| True / 1 | False / 0 | False / 0 |
| False / 0 | True / 1 | False / 0 |
| False / 0 | False / 0 | False / 0 |
OR gives 1 if at least one bit is 1. It gives 0 when both bits are 0.
| A | B | Result |
|---|---|---|
| True / 1 | True / 1 | True / 1 |
| True / 1 | False / 0 | True / 1 |
| False / 0 | True / 1 | True / 1 |
| False / 0 | False / 0 | False / 0 |
XOR gives 1 when the bits differ and 0 when they match.
| A | B | Result |
|---|---|---|
| True / 1 | True / 1 | False / 0 |
| True / 1 | False / 0 | True / 1 |
| False / 0 | True / 1 | True / 1 |
| False / 0 | False / 0 | False / 0 |
Powers of two and shifts#
You can skip this section and still follow the weather examples. To try the shifts yourself, switch your calculator to programmer mode if it has one. The built-in calculators on macOS and Windows have this mode, as do many Linux desktop calculators.
Every nonnegative integer power of two has exactly one 1 in its binary representation. The exponent gives the position of that 1, counting from zero at the right.
| n | Decimal | Binary |
|---|---|---|
| 0 | 1 | 0001 |
| 1 | 2 | 0010 |
| 2 | 4 | 0100 |
| 3 | 8 | 1000 |
| 4 | 16 | 0001 0000 |
| 5 | 32 | 0010 0000 |
| 6 | 64 | 0100 0000 |
| 7 | 128 | 1000 0000 |
| 8 | 256 | 0001 0000 0000 |
| 9 | 512 | 0010 0000 0000 |
| 10 | 1,024 | 0100 0000 0000 |
| 11 | 2,048 | 1000 0000 0000 |
Increasing the exponent by one moves the 1 one place to the left. Decreasing a positive exponent by one moves it one place to the right. A single set bit at position n has the value
A shift is a bitwise operation that moves bits by a given number of positions. A shift can replace multiplication or division by a power of two. Compilers often make that substitution themselves, so a shift written by hand may compile to the same instructions.
A left shift (<<) moves bits to the left and fills the empty positions on the right with zeros. In a four-bit illustration, shifting 0001 left by one gives 0010, or 2 in decimal. In a fixed-width unsigned integer, bits that move past the left edge are discarded.
A right shift (>>) moves bits to the right and discards bits that move past the right edge. An unsigned right shift fills the empty positions on the left with zeros. Shift 0010 right by one and you get 0001 again.
Start with 0001, which has a single 1 in the rightmost position. Each left shift by one place doubles the value. Shift left by n places and you get 2 to the power of n, provided the result fits. The table puts the two calculations side by side.
| n | Power (decimal) | Power (binary) | Shift (decimal) | Shift (binary) |
|---|---|---|---|---|
| 0 | 1 | 0001 | 1 | 0001 |
| 1 | 2 | 0010 | 2 | 0010 |
| 2 | 4 | 0100 | 4 | 0100 |
| 3 | 8 | 1000 | 8 | 1000 |
| 4 | 16 | 0001 0000 | 16 | 0001 0000 |
| 5 | 32 | 0010 0000 | 32 | 0010 0000 |
| 6 | 64 | 0100 0000 | 64 | 0100 0000 |
| 7 | 128 | 1000 0000 | 128 | 1000 0000 |
| 8 | 256 | 0001 0000 0000 | 256 | 0001 0000 0000 |
| 9 | 512 | 0010 0000 0000 | 512 | 0010 0000 0000 |
| 10 | 1,024 | 0100 0000 0000 | 1,024 | 0100 0000 0000 |
| 11 | 2,048 | 1000 0000 0000 | 2,048 | 1000 0000 0000 |
For nonnegative integers, shifts also give the same result as multiplying or dividing by a power of two, as long as the shift is valid and the product fits. Right shift gives the integer quotient. If y is the power of two, its base-2 logarithm gives the shift count. For multiplication, the shift is
For integer division, shift right by the same count.
Suppose we want to multiply 17 by 64.
The base-2 logarithm of 64 gives the shift count.
Shift 17 left by six places.
Multiplying 17 by 64 and shifting 17 left by six places both give 1,088. To divide a nonnegative integer by 64, shift it right by six places.
Weather flags in C#
Back to the weather. We can record whether it’s sunny, raining, snowing, or windy, and whether there’s thunder or lightning. Assign each condition a different bit. The value for each flag has a 1 in its own position and zeros everywhere else.
| Weather | Binary | Decimal | Exponent in 2ⁿ | Left shift |
|---|---|---|---|---|
| Sun | 0001 | 1 | 0 | 1 << 0 |
| Rain | 0010 | 2 | 1 | 1 << 1 |
| Snow | 0100 | 4 | 2 | 1 << 2 |
| Wind | 1000 | 8 | 3 | 1 << 3 |
| Thunder | 0001 0000 | 16 | 4 | 1 << 4 |
| Lightning | 0010 0000 | 32 | 5 | 1 << 5 |
You can define the flags with C macros or an enum.
#ifndef SUN
#define SUN 1 << 0
#endif // !SUN
#ifndef RAIN
#define RAIN 1 << 1
#endif // !RAIN
#ifndef SNOW
#define SNOW 1 << 2
#endif // !SNOW
#ifndef WIND
#define WIND 1 << 3
#endif // !WIND
#ifndef THUNDER
#define THUNDER 1 << 4
#endif // !THUNDER
#ifndef LIGHTNING
#define LIGHTNING 1 << 5
#endif // !LIGHTNINGenum WeatherEnum
{
SUN = 1 << 0,
RAIN = 1 << 1,
SNOW = 1 << 2,
WIND = 1 << 3,
THUNDER = 1 << 4,
LIGHTNING = 1 << 5
};Setting flags with OR#
You can set one flag or combine several. To store a single condition, assign its flag value to the integer. For sun alone, the value is 1 in decimal, 0001 in binary, or 1 << 0.
int current_weather = SUN; // Decimal: 1, binary: 0001, left shift: 1 << 0For rain and snow together, combine RAIN and SNOW with bitwise OR.
int current_weather = RAIN | SNOW; // Decimal: 6, binary: 0110RAIN has the value 0010 and SNOW has the value 0100. OR keeps a 1 wherever either flag has a 1, so the result is 0110 (6 in decimal). The RAIN and SNOW bits are both on. The diagrams use & in their labels to mean “and” in prose. The calculation itself uses OR.
0010 => RAIN
OR 0100 => SNOW
------------
0110 => RAIN & SNOWTo add wind, thunder, and lightning to the combination, include their flags in the OR expression. The result is 62, or 0011 1110 in binary.
int current_weather = RAIN | SNOW | WIND | THUNDER | LIGHTNING; // Decimal: 62, binary: 0011 1110 0000 0010 => RAIN
0000 0100 => SNOW
0000 1000 => WIND
0001 0000 => THUNDER
OR 0010 0000 => LIGHTNING
-----------------
0011 1110 => RAIN & SNOW & WIND & THUNDER & LIGHTNINGChecking flags with AND#
Use bitwise AND to test whether a flag is set. AND keeps only the bits that both operands have in common. If the result equals the flag you asked for, that flag is set. Start with a sunny day and check for SUN.
int current_weather = SUN; // Decimal: 1, binary: 0001, left shift: 1 << 0In C, == binds more tightly than &. Put parentheses around the AND expression so C evaluates it before comparing the result with SUN.
if ((current_weather & SUN) == SUN)
{
printf("Sunny\n"); // Runs because 0001 AND 0001 equals 0001.
}Both operands contain 0001. AND returns 0001, so the example prints “Sunny.”
0001 => current_weather
AND 0001 => SUN
------------
0001 => SUN A few days later, it’s raining and windy. The stored value is now 1010.
int current_weather = RAIN | WIND; // Decimal: 10, binary: 1010AND with SUN gives 0, so the equality check fails. The checks for RAIN and WIND return their respective flag values, so the code prints “Rain” and “Windy.”
if ((current_weather & SUN) == SUN)
{
printf("Sunny\n"); // Skipped
}
if ((current_weather & RAIN) == RAIN)
{
printf("Rain\n"); // Runs
}
if ((current_weather & WIND) == WIND)
{
printf("Windy\n"); // Runs
}Checking for sun
1010 => current_weather
AND 0001 => SUN
------------
0000 => 0 ( NOT SUN )
Checking for rain
1010 => current_weather
AND 0010 => RAIN
------------
0010 => RAIN
Checking for wind
1010 => current_weather
AND 1000 => WIND
------------
1000 => WIND Turning off a flag with XOR#
XOR returns 0 where both bits match and 1 where they differ. That lets us flip a bit that’s already on. Suppose the weather is still rainy and windy, with current_weather at 10 (1010).
int current_weather = RAIN | WIND; // Decimal: 10, binary: 1010The rain stops. Since the RAIN bit is already set, XOR with RAIN flips it from 1 to 0. The other bits stay as they were because the RAIN flag has zeros in those positions.
current_weather = current_weather ^ RAIN; // Decimal: 8, binary: 1000The result is 8 (1000). Run the same checks again and only “Windy” prints.
if ((current_weather & SUN) == SUN)
{
printf("Sunny\n"); // Skipped
}
if ((current_weather & RAIN) == RAIN)
{
printf("Rain\n"); // Skipped
}
if ((current_weather & WIND) == WIND)
{
printf("Windy\n"); // Runs
} 1010 => current_weather
XOR 0010 => RAIN
------------
1000 => WIND ONLY XOR toggles the selected bit. If RAIN is already off, the same operation turns it on. To clear it regardless of its current value, AND with the bitwise complement of the flag (written in C as current_weather & ~RAIN).
The flags you store in an integer can represent unrelated properties. Define which property belongs to each bit and use those assignments consistently.
Discord permissions#
Discord uses bitwise flags for API permissions. The Chinese version of this article described 50 permissions spanning 1 << 0 through 1 << 49. Discord now lists flags above bit 49. The flag for sending polls still occupies bit 49, with a value of 562,949,953,421,312. Discord developer documentation