DEV Community

n350071πŸ‡―πŸ‡΅
n350071πŸ‡―πŸ‡΅

Posted on

5

bit operation in the wild

I've never used bit operation in my life.
But currently, I've got a chance to know how it is good.

I will develop this post, but publish it first anyway.

case.1 For day matching operation

Define and WHY

You can define days like this.

MON = 1
TUE = 2
WED = 4
THU = 8
...

Maybe, you've got a question, WHY?
Let's see it in bit world.

MON.to_s(2).to_i #=>    1
TUE.to_s(2).to_i #=>   10
WED.to_s(2).to_i #=>  100
THU.to_s(2).to_i #=> 1000
...

PROS

If a user check MON and WED, it's easy to calculate now.

MON | WED #=> 5 ( MON = 1, WED = 4 )

The bit of 5 is 101 which made of 001 and 100.
It's easy πŸŽ‰

Use it with Date

Date.today          #=> Thu, 30 Jan 2020
Date.today.wday     #=> 4
MON = 1 # = 2**0
TUE = 2 # = 2**1
WED = 4 # = 2**2
THU = 8 # = 2**3
...

So, you can get the bit of the date from Date object.

2**(Date.today.wday - 1) #=> 8

Take the multi case of the date by the 1 operation

You can filter the cases include "WED" by bitwise &.

Image is like this.

0000 #0 NAN
0001 #1 MON
0010 #2 TUE
0011 #3 TUE and MON
0100 #4 WED
0101 #5 WED and MON
0110 #6 WED and TUE
0111 #7 WED and TUE and MON

&&&&

0100 # WED

Example: 3 & 4 #=> 0 ( TUE and MON & WED )
Because,

0011 # TUE and MON
&&&&
0100 # WED
----
0000

Example: 5 & 4 #=> 4 ( WED and MON & WED )
Because,

0101 # TUE and MON
&&&&
0100 # WED
----
0100 #=> 4
0 & 4 #=> 0
1 & 4 #=> 0
2 & 4 #=> 0
3 & 4 #=> 0
4 & 4 #=> 4
5 & 4 #=> 4
6 & 4 #=> 4
7 & 4 #=> 4

So, we can check it is valid of not by '=='

3 & 4 == 4 #=> 0 == 4 #=> false
5 & 4 == 4 #=> 4 == 4 #=> true

By this mechanism, you can easily make sure the date matches the day?

Use it in SQL, Relation, ActiveRecord, WHERE

Now, you can understand it. ( SQL also has the bitwise & operator. )

.where("user_selected_days & ? = ?", 2**(Date.today.wday - 1), 2**(Date.today.wday - 1))

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here β†’

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay