Learn C · lesson 58 of 60 · about 10 minutes
Bitwise Operators
Work with the individual 1s and 0s inside a number, and pack several on/off flags into one int.
What you'll learn
- Read numbers in binary
- Use & | ^ and ~ on bits
- Shift bits with << and >> and use bit flags
The night's alerts
Overnight, the servers raised alerts. The report reads their names, one per line, cpu, disk or net, until end, and keeps all of them in one int: Alerts: cpu net (code 5). An alert raised twice is still one alert, and a name that isn't an alert gets No alert called fan. Each kind of alert is one bit of the number, a flag.
Numbers are bits
Every int is stored as bits, 1s and 0s. 6 is 110 in binary: 4 + 2 + 0.
Bitwise operators work on each bit separately:
- a & b is 1 where both bits are 1
- a | b is 1 where either bit is 1
- a ^ b is 1 where the bits are different
- 1 << n is a 1 moved n places left, which is 2ⁿ; >> moves bits right
6 and 3
#include <stdio.h>
int main(void) {
int a = 6; /* 110 */
int b = 3; /* 011 */
printf("%d %d %d\n", a & b, a | b, a ^ b);
printf("%d %d\n", 1 << 4, 40 >> 2);
return 0;
}Output
2 7 5
16 10Flags in one number
Each bit can be an on/off switch, a flag. Give each flag its own bit, like READ = 1 << 0, WRITE = 1 << 1.
- Turn a flag on with
flags |= WRITE - Turn it off with
flags &= ~WRITE(~flips every bit) - Test it with
if (flags & WRITE)
File permissions
#include <stdio.h>
enum { READ = 1 << 0, WRITE = 1 << 1, RUN = 1 << 2 };
int main(void) {
int perms = READ | RUN;
printf("write? %d\n", (perms & WRITE) != 0);
perms |= WRITE;
perms &= ~RUN;
printf("read %d, write %d, run %d\n", (perms & READ) != 0, (perms & WRITE) != 0, (perms & RUN) != 0);
printf("%d\n", perms);
return 0;
}Output
write? 0
read 1, write 1, run 0
3One bit for each alert
ALERT_CPU is 1 << 0, ALERT_DISK is 1 << 1 and ALERT_NET is 1 << 2, so each one has a bit of its own. alerts |= flag turns one on, and turning it on twice changes nothing, so a repeated alert isn't counted again. print_alerts tests each bit with & and lists the names, and the code is just the number all the bits make: cpu and net are 1 + 4 = 5.
Tip
Don't mix up & with && or | with ||. The doubled ones are for true/false conditions; the single ones work bit by bit.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.