Get Bit

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.

1 << 0 → 0000 0001 # for the 0th bit 1 << 1 → 0000 0010 # for the 1st bit 1 << 2 → 0000 0100 # for the 2nd bit ... 1 << 7 → 1000 0000 # for the 7th bit

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.

& 0101 1101 0010 0000 ----------- 0000 0000
& 0101 1101 0100 0000 ----------- 0100 0000

Here's an implementation in code:

def bit_value(number, bit): ''' Returns the value of the bit at index 'bit' in 'number' ''' mask = 1 << bit if number & mask != 0: return 1 return 0

What's next?

If you're ready to start applying these concepts to some problems, check out our mock coding interview questions.

They mimic a real interview by offering hints when you're stuck or you're missing an optimization.

Try some questions now

. . .