Bit Manipulation · Pattern 1 of 6
Bit basics: read, test and build numbers bit by bit
n & 1 reads the lowest bit and n >> 1 drops it, so a loop can walk through every bit. (n >> k) & 1 tests one bit, and res = (res << 1) | bit builds a number one bit at a time.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Convert between decimal and binary (or another base)
- Is bit k set? Is the number odd?
- Reverse, add or validate numbers without the usual operators
- Read a number given as a list of bits
The template
String toBinary(int n) { // n >= 0
if (n == 0) return "0";
StringBuilder sb = new StringBuilder();
for (; n > 0; n >>= 1) sb.append(n & 1); // lowest bit first
return sb.reverse().toString();
}
boolean isKthBitSet(int n, int k) {
return ((n >> k) & 1) == 1; // bring bit k to the bottom
}
int reverseBits(int n) { // the 32 bits, treated as unsigned
int res = 0;
for (int i = 0; i < 32; i++) {
res = (res << 1) | (n & 1); // shift the next bit in
n >>>= 1; // >>> so no sign bits come in
}
return res;
}
int getSum(int a, int b) { // a + b without + or -
while (b != 0) {
int carry = (a & b) << 1; // where both bits are 1
a ^= b; // sum without the carry
b = carry;
}
return a;
} def to_binary(n): # n >= 0
if n == 0:
return "0"
bits = []
while n > 0:
bits.append(str(n & 1)) # lowest bit first
n >>= 1
return "".join(reversed(bits))
def is_kth_bit_set(n, k):
return ((n >> k) & 1) == 1 # bring bit k to the bottom
def reverse_bits(n): # the 32 bits of n
res = 0
for _ in range(32):
res = (res << 1) | (n & 1) # shift the next bit in
n >>= 1
return res
def get_sum(a, b): # a + b without + or -
mask = 0xFFFFFFFF # Python ints are unbounded: emulate 32 bits
a, b = a & mask, b & mask
while b:
a, b = (a ^ b) & mask, ((a & b) << 1) & mask
return a if a <= 0x7FFFFFFF else ~(a ^ mask) # back to a signed value string toBinary(int n) { // n >= 0
if (n == 0) return "0";
string s;
for (; n > 0; n >>= 1) s += char('0' + (n & 1)); // lowest bit first
reverse(s.begin(), s.end());
return s;
}
bool isKthBitSet(int n, int k) {
return ((n >> k) & 1) == 1; // bring bit k to the bottom
}
uint32_t reverseBits(uint32_t n) { // unsigned: >> shifts in zeros
uint32_t res = 0;
for (int i = 0; i < 32; i++) {
res = (res << 1) | (n & 1); // shift the next bit in
n >>= 1;
}
return res;
}
int getSum(int a, int b) { // a + b without + or -
while (b != 0) {
unsigned carry = (unsigned)(a & b) << 1; // unsigned: no overflow on shift
a ^= b; // sum without the carry
b = (int)carry;
}
return a;
} function toBinary(n) { // n >= 0
if (n === 0) return "0";
let s = "";
for (; n > 0; n >>= 1) s = (n & 1) + s; // lowest bit first, prepended
return s;
}
function isKthBitSet(n, k) {
return ((n >> k) & 1) === 1; // bring bit k to the bottom
}
function reverseBits(n) { // the 32 bits, treated as unsigned
let res = 0;
for (let i = 0; i < 32; i++) {
res = (res << 1) | (n & 1); // shift the next bit in
n >>>= 1; // >>> so no sign bits come in
}
return res >>> 0; // read the result as unsigned
}
function getSum(a, b) { // a + b without + or -
while (b !== 0) {
const carry = (a & b) << 1; // where both bits are 1
a ^= b; // sum without the carry
b = carry;
}
return a;
} The variations
-
1Convert between bases
n & 1(orn % 2) is the next digit andn >> 1moves on; reverse at the end. Going the other way,res = res * 2 + bit(or(res << 1) | bit) reads bits from the most significant end. Base −2 is the same loop with remainders fixed to 0 or 1.Now you solve -
2Test one bit
Shift the bit you want to the bottom and AND with 1, or AND with the mask
1 << k. Odd or even is just bit 0. UTF-8 bytes are told apart by their top bits, so the same test reads each byte's header.Now you solve- Odd or Even Easy Stuck? ▶ video
- UTF-8 Validation Medium Stuck? solution
-
3Shift bits in and out
Take bits off one number with
n & 1andn >>> 1, and push them onto another with(res << 1) | bit. Adding without+is the same kind of loop: XOR adds without carrying, and(a & b) << 1is the carry, until no carry is left.Now you solve
Mistakes to avoid
- Writing
n & 1 << kand getting the precedence wrong: put brackets around every bit expression. - Reversing bits with
>>in Java or JavaScript: a set top bit drags ones in from the left. Use>>>. - In JavaScript, returning a reversed 32-bit value without
>>> 0gives a negative number when the top bit is 1.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.