![A stick figure smiling](/images/welcome.jpg)
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!
![Image of a comic. To read the full HTML alt text, click "read the transcript".](/images/uploads/bit-tricks.png)
read the transcript!
title: how bitwise operations are used
panel 1
Binary formats often pack information into bytes very tightly to save space.
Bitwise operations are what you use to encode or decode data into a binary format.
Here’s how and, or, left shift, and right shift are used for encoding and decoding.
panel 2: check/set bit flags
set bit flags with or: x = x | 0x04
check bit flags with and:: if (x & 0x04 != 0) {}
(snippets are C code)
panel 3: bit masking
“bit masking” means using & to set some bits in a number to zero. For example, & 0xFFFF zeroes all except the last 16 bits:
masked = x & 0xFFFF
panel 4: unpack/pack bits
for example, to unpack the leftmost 2 bits of a byte: first_two_bits = x >> 6
(>> is right shift)
for example, to pack 01 into the left 2 bits of a byte: result = (1 << 6)
(<< is left shift)
panel 5: checksums and encryption
xor is used for checksums and encryption. Here’s what encrypting with xor in Python looks like:
```
text = b”secret message” for (t, k) in zip(text, key): encrypted += t ^ k ```
Saturday Morning Comics!
Want another comic like this in your email every Saturday? Sign up here!