| Resources | |||||
|---|---|---|---|---|---|
| CPH | |||||
| CF | Great explanation by Errichto | ||||
| GFG | The same operators are used in java and python | ||||
Overview
Below, we'll introduce a couple of concepts necessary for understanding problems with bitwise operators.
Numbers in Base Two
Whereas we are accustomed to base ten (decimal), in computers, numbers are stored in base two (binary): the only digits are zero and one. Each digit in binary is known as a bit. The rightmost bit is called the least significant bit (LSB), while the leftmost bit is referred to as the most significant bit. When we refer to bits, we usually refer to LSBs. The th bit is typically the th LSB, zero-indexed. You may have heard of bytes: a byte is eight bits.
For some problems, you will need to convert numbers between decimal and binary.
To convert from decimal to binary, we find the largest power of two less than or equal to the initial decimal number, subtract that from our decimal, then repeat until our decimal is zero. We keep track of the exponent associated with the power of two. At those bits (counting from the right), we set the bit (i.e., make it one). All other bits are zeros, and we can omit the leading zeros.
Example:
d = 5, 2^2 = 4 d = 5 - 4 = 1, 2^0 = 1
Now, note the powers of two in this example: 2 and 0. Thus, the th and nd positions from the right are set to .
This gives us = .
To convert from binary to decimal, the th bit is given a weight . We add the weight multiplied by the bit to our result.
From the previous example, .
You may be wondering how we can represent negative numbers in binary. Although there are other ways, such as sign and magnitude, the most common way to do this is by using a technique called two's complement.
In two's complement, the MSB has a weight of instead of . Every other bit is . For example, will be . This is also the reason a standard C++ int's max is : a standard C++ int has 32 bits, and the MSB is a negative weight while the other 31 bits are positive weights.
In most problems, you just need to be familiar with the unsigned representation, not two's complement.
Bitwise Operators
Bitwise operators act bit by bit. Most bitwise operators are binary,
meaning they take two inputs: AND &, OR |, XOR ^, and shifts.
The only unary bitwise operator (an operator that takes one input)
is NOT ~.
AND (
&) - evaluates whether both bits are1.1 & 1 = 1but1 & 0or0 & 0equal0.OR (
|) - evaluates whether either bit is1.1 | 1 = 1and1 | 0 = 1, but0 | 0 = 0.XOR (
^) - exclusive or, returns1when only one bit is1.1 ^ 0 = 1but1 ^ 1 = 0.NOT (
~) - effectively flips the bit:~1 = 0and~0 = 1.
Bitwise operations can be applied to larger strings of bits, with binary bitwise operations
comparing the strings bit by bit. For example, 1111 & 1010 = 1010. Unary bitwise operators are applied
bit by bit: ~111 = 000. More information/examples can be found here.
In actual programming, the bits aren't just the bits . Instead, there are many leading zeros (depending
on whether your language has integers as or bits, or perhaps another representation). Thus, ~111 might
return .
The truth table below is useful to understand the binary bitwise operators.
A | B | A & B | A | B | A ^ B |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 0 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 0 |
A | ~A |
|---|---|
| 0 | 1 |
| 1 | 0 |
Bitshifts
Using the bitshift operators >> and <<, we can "shift" our binary representation's
bits to the left or to the right. These are binary operators! The first input is
the binary number to shift, and the second input is how many places to shift that number's
bits by.
A left shift << adds a 0 bit to the LSB. Example:
10101 << 1is10101010101 << 2is1010100
A left shift by is equivalent to multiplying the number by .
Proof
Be careful not to overflow with a left shift! As an example, in C, integers typically only have bits, so left shifting
too much (like 1 << 32) may overflow! A left shift by adds more bits to the representation (ignoring leading
zeros).
Whereas you need to worry about 32 and 64 bit integers in other languages, you don't need to in Python! Just remember that a very large shift may cause an overflow.
A right shift is the opposite of a left shift. A right shift by removes the th through th LSBs.
There are two kinds of right shifts, determining which digit gets added to be the MSBs. An arithmetic right shift is used for signed numbers, while a logical right shift is used for unsigned numbers. Arithmetic right shifts add a copy of the MSB when right shifting, and thus preserve the sign. Logical right shifts add zero. This is due to how signed binary integers are typically encoded in two's complement.
However, these little details usually won't be tested on. The key idea to remember is what happens to the digits that are in the number you're shifting.
A right shift by is equivalent to the floor of the number divided by .
Proof
Bitmasks
We can create a bitmask to manipulate/read certain bits from a number. Each digit acts as a "flag" where indicates an active flag and indicates an inactive flag.
Recall how most bitwise operators are binary, meaning they take two inputs. Our first input to our operator is , while the second input is a bitmask.
Like previous concepts, bitmasks are best explained with examples.
Let's say we want to extract the LSB of a number. Then, we can have our bitmask be and use the operator.
- If we include some of the leading zeros of , we get . This means that only the LSB is active while all other flags are inactive
- Consider a number . When we do , the result is , which is the LSB!
Example: Shifts and Masks
Now, consider this question: how can we extract the -th least significant bit?
Hint 1
Hint 2
Solution
Summary
It is best to understand how to derive these, but remembering these may be helpful.
# extract the ith bit(b >> i) & 1# set the ith bitb |= 1 << i# clear the ith bitb &= ~(1 << i)# toggle the ith bitb ^= 1 << i
Focus Problem – try your best to solve this problem before continuing!
Solution - Take a Guess
In fact, we can figure out the sum of two numbers using just their AND, OR and XOR values! Suppose we know their XOR values, we can use the following property:
The proof is as follows:
is essentially just in base but we never carry over to the next bit. Recall a bit in is only if the bit in is different from the bit in , thus one of them must be a . However, when we add two bits, we yield a , but we do not carry that to the next bit. This is where comes in.
is just the carry bits themselves, since a bit is only if it's a in both and , which is exactly what we need. We multiply this by to shift all the bits to the left by one, so every value carries over to the next bit.
To acquire the XOR values of the two numbers, we can use the following:
The proof is as follows:
Recall a bit in is only if the bit in is different from the bit in . By negating , the bits that are left on are in the following format:
- If it's in and in
- If it's in and in
- If it's in and in
Now this looks pretty great, but we need to get rid of the third case. By taking the bitwise AND with , the ones that are left on is only if there is a in either or . Obviously, the third case isn't included in since both bits are off, and we successfully eliminate that case.
Now that we can acquire the sum of any two numbers in two queries, we can easily solve the problem. We can find the values of the first three numbers of the array using a system of equations involving their sum (note ). Once we have acquired their independent values, we can loop through the rest of the array.
def ask(s: str, a: int, b: int) -> int:print(f"{s} {a} {b}", flush=True)return int(input())def sum(a: int, b: int) -> int:""":return: the sum of the elements at a and b (0-indexed)"""a += 1b += 1and_ = ask("and", a, b)
Example - Addition
Now let's take a look at implementing addition and multiplication using only bitwise operators. Before we do so, though, try implementing addition using bitwise operators on your own! You can test your implementation here.
Solution - Addition
If we perform addition without carrying, then we are simply performing the XOR
(^) operator. Then, the bits that we carry over are those equivalent to in
both numbers: .
def add(a: int, b: int) -> int:while b > 0:carry = a & ba ^= bb = carry << 1return a
Example - Multiplication
Now try implementing multiplication using bitwise operators! If you want to test your implementation of multiplication, you can do so here.
Solution - Multiplication
For simplicity, we will use the sum functions defined above. If we divide up
into , we get the following:
(This same idea is used in binary exponentiation!)
def prod(a: int, b: int) -> int:c = 0while b > 0:if b & 1:c = add(c, a) # Use the addition function we coded previouslya <<= 1b >>= 1return c
XOR Operation
Perhaps one of the most common binary operations in practice is bitwise xor. The special property that differentiates it from the other bitwise operations is that xor is its own inverse, i.e. .
Focus Problem – try your best to solve this problem before continuing!
Explanation
Let's analyze the bits of each xor-sum independently. In this case, we'll check for every bit position, i.e. for every power of two, whether or not it's set in the xor-sum of every contiguous subsequence. This way, we transformed the problem into counting the number of subsequences with non-zero xor-sum; this will be applied on the array form by the bits on the same position in all the values.
Implementation
Time Complexity:
n = int(input())v = list(map(int, input().split()))res = 0"""For every bit positioncheck if it's set on in the xor-sum of every subsequence"""for i in range(30):s = 0
| Status | Source | Problem Name | Difficulty | Tags | ||
|---|---|---|---|---|---|---|
| CF | Easy | Show TagsBitwise, Greedy | ||||
| CF | Easy | Show TagsBitwise | ||||
| CF | Easy | Show TagsBinary Search, Bitwise, Complete Search | ||||
| AC | Easy | Show TagsBitwise | ||||
| CF | Easy | Show TagsBitwise, Sorting, Trie | ||||
| Silver | Easy | Show TagsBitwise, Complete Search | ||||
| CF | Easy | Show TagsBitwise | ||||
| Silver | Medium | Show TagsBitwise, Graphs | ||||
| CF | Medium | Show TagsBinary Search, Bitwise, Prefix Sums | ||||
| CF | Medium | Show TagsBitwise, Prefix Sums | ||||
| CSES | Medium | Show TagsBitwise, PIE | ||||
| CF | Medium | Show TagsBitwise, Greedy, Math | ||||
| Silver | Medium | Show TagsBitwise | ||||
| Silver | Medium | Show TagsBitwise, Prefix Sums | ||||
| CF | Hard | Show TagsBitwise, Interactive | ||||
Quiz
Which of the following will set the kth bit of int x as true? Assume you do not know what the value of the kth bit currently is.
Module Progress:
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!