NOTE: use 1L for shifting with larger sized numbers
0xF -> 1111
0x7 -> 0111
0x3 -> 0011
0x1 -> 0001
https://graphics.stanford.edu/~seander/bithacks.html http://bits.stephan-brumme.com/ http://aggregate.org/MAGIC/
~(x & 1)
x && !(x & x - 1)
~0
~0u
x & 0x0000FFFF
x | 0x...
~0 << n
~0 >> n
~(~0 << n)
~(~0 >> n)
(considers index p and n elements to its right and moves to rightmost position, i.e. for p = 4 and n = 3, initial elements 4,3,2 will be all the way right)
x >> (p + 1 - n)
x |= (1 << n)
x &= ~(1 << n)
x ^= (1 << n)
x & (1 << n)
unsigned y = (x << n) | (x >> (32 - n))
unsigned y = (x << n) | (x >> (-n & 31))
v &= v - 1
x &= ~(x - 1)
x ^= (1L << i) | (1L << j)
// Kernighan
for (c = 0; v; c++) {
v &= v - 1;
}
int sign = -(v < 0);
// not portable
int sign = v >> (sizeof(int) * CHAR_BIT - 1);
return ((x ^ y) < 0);
const int mask = v >> sizeof(int) * CHAR_BIT - 1;
return (x ^ mask) - mask;
return y ^ ((x ^ y) & -(x < y)); // min(x, y)
return x ^ ((x ^ y) & -(x < y)); // max(x, y)
return v && !(v & (v - 1));
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
++x;
return x;
x ^ 0 == x
x ^ ~0 == ~x
x ^ x == 0
(x ^ y) ^ z == x ^ (y ^ z)
x ^ y == y ^ x
x ^= y
y ^= x
x ^= y
// or
x = x ^ y;
y = x ^ y;
x = x ^ y;
x ^ y == (~x & y) | (x & ~y)
0010 2
0001 1
0000 0
1111 -0
1110 -1
0001 1
0000 0
1111 -1
1110 -2
0101 -> 1010
bitwise NOT (~) of number then add 1 (ignore overflow of two's complement of 0)
returns the numerical complement