Bit Manipulation (Part I)

Bit Manipulation is rarely asked during an interview. But it’s good to know all the basic concepts below in case you get asked. Personally, I haven’t run into any LeetCode questions other than the following concepts.

I. Basic concepts

1. and, or, not, xor

2. shift

3. Length

4. bin(), convert an integer to a binary string in Python

5. Base

‘b’ is in Python means binary-based

6. count()

7. Negative, two’s complement

invert all the bits and add 1

E.g. -5

E.g. -6

E.g. -7

8. a & (-a), Get the rightmost 1-bit

E.g. 5&(-5)

E.g. 6&(-6)

E.g. 7&(-7)

9. a & (a-1), Brain Kernighan’s algorithm, to turn off the rightmost bit of 1

E.g. 4&(4–1)

E.g. 5&(5–1)

E.g. 6&(6–1)

E.g. 7&(7–1)

Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store