A brief introduction
Maxim Rebguns
November 2023
Why would we need to manipulate individual bits?
A | B | ? |
---|---|---|
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
Performs an AND operation on each bit:
011010100
& 101001101
---------
001000100
A | B | ? |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
Performs an OR operation on each bit:
011010100
| 101001101
---------
111011101
A | B | ? |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
Performs an XOR operation on each bit:
011010100
^ 101001101
---------
110011001
A | ? |
---|---|
0 | 1 |
1 | 0 |
Performs a NOT operation on each bit:
~ 011010100
---------
100101011
Allows you to shift all bits of a number to the left or right by another number.
0010110 >> 10 becomes 0000101
0010110 << 10 becomes 1011000
Let’s look at an application of bitwise operators that is often used for representing grids in games: bitboards
Goal: Create a grid representing the tic-tac-toe board.
o | x | x |
x | ||
o | o |
char
, but 252
of those bits would still be wasted.What if we represented the board as two binary numbers, one for each side?
1 o | 2 x | 3 x |
4 x | 5 | 6 |
7 o | 8 o | 9 |
Get an intuitive understanding: https://tearth.dev/bitboard-viewer/
Get a bitboard representing all taken positions:
Check if a player’s move is valid:
There are 8 ways to win in tic-tac-toe. You can represent these 8 board positions as bitboards, and then AND them with the player’s positions to see if they won:
Bitwise operators allow you to manipulate bits efficiently, which is what makes this a great methods for complex games like chess.
This work accessible here by Maxim Rebguns is licensed under CC BY 4.0