Building on Ethereum can be expensive, and many times it intuitive to gain control over your code and one way to achieve this is by utilzing bit operations. Many developers use it as a means of optimization, expecially in the case of ethereum when you code now cost you money.
Here I'd be explaining a program I wrote not long ago, just so you'd gain an understanding of a simple use case of bit operations.
Also, I assume you understand how to work with bitwise operators, and if you don't check out my article on how they work here.
Tic-tac-toe is a 2 player game where players take turns to make a finite amount of moves until either all moves has been exhausted (its a draw) or a player has won. Here is a typical tic-tac-toe game.
From the example above, 2 players are represented using to letters X
and O
and each take turns to win and also prevent the other player from winning.
With zero knowledge of bit operations, here is a typical representation of a game session:
However, we don't need 8 bits to store data for each position on the board in uint8[9] board;
since 8 bits is allocated to each position which gives us () bits for a board that can be packed in just 18 bits, bool turn;
is binary i.e 1 for true
and 0 for false
; Also, bool hasGameEnded;
, bool playerOneWon;
, playerTwoWon
and isDraw
are 4 situation a game can be and this can be represented in just 2 bits:
10
),00
),01
),11
).So here is how we'd store a game in bits
From the example above you'd see the operation gameBoard | 1 << 20
, this basically creates sort of a new 21 bits space for a new game. So here is a little break down of what is happening:
When a player chooses to make a move he'd choose which place to play the move and indicate that it's the next players turn. Each move would be represented by a number like so:
So typically a game play would be:
Given that player1 is X
and player2 is O
So I think you have a base understanding of how it works now, back to coding.
Now, players can make moves and switch turns but they'd keep playing if we don't stop them when a player has won or it's a draw. So a player's win can either be HORIZONTAL
, VERTICAL
or DIAGONAL
. Representing these in the board would look like:
Having a good knowledge of bit operations is really great! also keep in mind almost all programming languages implement the operations, so it's basically applicable in most languages. These tricks are great but many times they have extremely niche applications, and that is up to you to choose when and when not to apply them.
Also, check out a similar article by fivenine here as it inspired this article.
If you found this helpful, consider following me on Twitter @0xosas.