Skip to Content
Navigation:

A stick figure smiling

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".

browse more comics! get the zine!
read the transcript!

bitwise operations operate one bit at a time

The results can be surprising when you write them in base 10: 8 & 3 = 0

but in binary it makes more sense:

00001000 (8)
& 00000011 (3)
= 00000000

&

Bitwise and: the result is 1 if BOTH bits are 1

1 & 1 = 1
1 & 0 = 0
0 & 0 = 0
11 & 10 = 10

|

Bitwise or: the result is 1 if EITHER bit is a 1

1 | 1 = 1
1 | 0 = 1
0 | 0 = 0
11 | 10 = 11

^

Bitwise xor: the result is 1 if EXACTLY ONE bit is a 1

1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 0 = 0
11 ^ 10 = 01

~

Bitwise not: FLIP all the bits

~0 = 1
~1 = 0
~10 = 01

<<

Left shift: add 0s to the end

1110 <<< 3 = 1110000

<< n is the same as multiplying by 2^n

>>

Right shift: chop bits off the end 01100001 >> 2 = 00011000

>> n is the same as dividing by 2^n

there are actually two right shifts

unsigned right shift

253 >> 1 = 126
11111101 -> 01111110

always pad on the left with a 0

signed right shift

-3 >> 1 = 2
11111101 -> 11111110

if the number is negative, pad on the left with 1 instead of a 0

In some languages, unsigned right shift is >>>. In other languages, both right shifts are >> and the integer’s type determines which is used.

Saturday Morning Comics!

Want another comic like this in your email every Saturday? Sign up here!

I'll send you one of my favourite comics from my archives every Saturday.
© Julia Evans 2024 | All rights reserved (see the FAQ for notes about licensing)