Table of contents:
Bit tricksA few bit trick for integer arithmetic, some are obvious but they are there because they are used as base for more complex stuff. Integers are assumed to be 32 bits, so you need to adujst some things for other sizes. I got most of this stuff from The Multimedia Guru: http://guru.multimedia.cx
Normalize to 0/1
r = !!a
r = a != 0
0/1 to mask
r = -a
0/1 to inverted mask
r = a-1
Conditional bitwise not
r = a ^ mask
Conditional negate
r = (a+mask) ^ mask
Conditional add/sub
r += a & mask
Conditional assign
r = ((a ^ b) & mask) ^ b
Absolute value
s = a >> 31
r = (a+s) ^ s
Modulo with unsigned power of 2
r = a & (b-1)
Modulo with signed power of 2
s = a>>31
r = ((((a+s) ^ s) & (b-1)) + s) ^ s
Average without overflow
r = (a & b) + ((a ^ b) >> 1)
Is an unsigned a power of 2
r = (a & (a-1)) == 0
|