Bit manipulation
Битовые трюки
Working directly with the bits of an integer lets you use one number to store several on/off settings or test properties such as whether the number is a power of two.
Think of an integer as a row of switches
In binary, each position holds a 0 or a 1. Number the positions from the right, starting at zero: binary 1010 has bits 1 and 3 set. If each position stands for a setting, that single number records which settings are on. Bitwise operators are the tools that act on those positions; bit manipulation is how you use them to represent data or solve a problem.
Use a mask to pick out bits
A bit mask marks the positions you care about with 1s. The expression 1 << i shifts a single 1 left by i places. Given that mask m and a value x:
(x & m) != 0checks whether the bit is set. AND (&) keeps a1only where both inputs have one.x | msets the bit. OR (|) needs a1in either input.x & ~mclears the bit. NOT (~) flips the mask so the selected position is the one that AND clears.x ^ mtoggles the bit. XOR (^) produces a1where the two input bits differ.
A mask can select several positions at once. For example, a program that stores display settings in an integer could check two settings together with (settings & required) == required. Comparing the result to zero instead would tell you whether any of the required settings are on, not whether all are on.
Example: count the set bits
For a positive integer, subtracting one flips its rightmost 1 to 0 and turns all the zeros to its right into ones. AND the result with the original and that rightmost 1 disappears, while every other bit stays as it was. For example, binary 1100 & 1011 gives 1000.
def count_set_bits(x: int) -> int:
if x < 0:
raise ValueError('expected a nonnegative integer')
count = 0
while x:
x &= x - 1
count += 1
return count
The loop runs once per set bit rather than once per position. For ordinary Python code, use x.bit_count() for nonnegative integers unless you have a reason to implement the count yourself.
Where it helps and what to watch for
Masks are useful when reading packed fields in a binary file, working with hardware registers, or representing subsets in dynamic programming. If a compact representation isn't needed, a set or named Boolean fields may be clearer. Check your language's integer and shift rules before porting code: JavaScript bitwise operations on Number, for instance, use 32-bit representations. A mask that works on a larger Python integer may not work the same way there.
In a coding interview
A common follow-up is to test whether an integer is a power of two. A positive power of two has exactly one set bit, so clearing its lowest set bit must leave zero: x > 0 and (x & (x - 1)) == 0. Explain why the positive check is necessary: zero also passes the AND test. When discussing complexity, state whether you are assuming fixed-width machine integers. An operation on an arbitrary-precision integer need not take constant time.