Here's a preview from my zine, How Integers and Floats Work! If you want to see more comics like this, sign up for my saturday comics newsletter or browse more comics!
read the transcript!
bit flags
bit flags are a clever way to store lots of information in one integer
If you have many options which are true or false, you can encode them all into an integer, with 1 bit for each option. 32 bits 32 options!
For example, some of the bit flags the open function in C uses: - nofollow - append - truncate - create - write only - read write
(this is on Linux)
where you’ll see bit flags
In libc, the open, socket, and mmap functions use bit flags to pass options.
The TCP and UDP protocol headers both have a flags field which has bit flags.
bit flags are used a lot in C code
Here’s some C code that opens a new file:
fd = open("file.txt", O_RDWR | O_CREAT, 0666);
O_RDWR
is: 00000010
O_CREAT
is: 01000000
O_RDWR | O_CREAT
is: 01000010
You can check if a bit flag is set in C like this:
if (flags & O_RDWR) { ... }
fun example: tic tac toe!
Here’s a way to encode the state of a tic tac toe game in 18 bits:
x positions:
100
010
010
O positions:
010
001
100
Saturday Morning Comics!
Want another comic like this in your email every Saturday? Sign up here!