We can get the value of a specific bit using a left shift with an and.
First, we'll create a mask by taking 1 and shifting it left until the set bit is at the index we want to test.
Then, we'll & the shifted 1 with the value we're testing. If the result is zero, then the bit is 0; otherwise, it's 1.
Here's an implementation in code:
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!