You are on page 1of 1

Bit Hacks Cheat Sheet

by JSondhof via cheatography.com/30576/cs/9135/

C/C++ bitwise operations Single bit operations

& AND y = x | Set the nth bit

| OR (1<​<n)

^ XOR y = x & ~ Unset the nth bit

~ NOT (1<<n)

<< SHIFT (left) y = x ^ Toggle the nth bit

>> SHIFT (right) (1<​<n)

return x & Test if the nth bit is set


Useful snippets
(1<​<n)

Counting (c) bits set in x y = x & (x- Turn off rightmost 1bit
for (c = 0; x; c++) { x &= vx- 1; 1)
}
y = x & (- Isolate rightmost 1bit

Computing parity in parallel (32 Bit) x)

x ^= x >> 16; x ^= x >> 8; x ^= x y = x | (x- Right propagate rightmost


>> 4; x &= 0xf; return (0x6996 >> 1) 1bit (fill in ones)

x) & 1;
y = x | Turn on rightmost 0bit
(x+1)
Integer arithm​etics
y = ~x & Isolate rightmost 0bit
x = y << n Multiply by n times (x+1)
2

x = y >> n Divide by n times


2

return (x & 1) == 0 Is x even?

return (x && !(x & Is x power of 2?


(x - 1)))

return (x ^ y) < 0 Has x opposite


sign than y?

y ^ ((x ^ y) & -(x min(x,y)


< y))

x ^ ((x ^ y) & -(x max(x,y)


< y))

By JSondhof Not published yet. Sponsored by ApolloPad.com


cheatography.com/jsondhof/ Last updated 16th September, 2016. Everyone has a novel in them. Finish Yours!
Page 1 of 1. https://apollopad.com

You might also like