C code | Description | Obtained from |
---|---|---|
a ^= b; b ^= a; a ^= b; | Swap a and b around | ComputerShopper |
c & -c or c & (~c + 1) | return first bit set | Eivind Eklund |
~c & (c + 1) | return first unset bit | Eivind Eklund |
unsigned i, c = <number>; | i will contain the number of bits set in c | Eivind Eklund |
m = (m & 0x55555555) + ((m & 0xaaaaaaaa) >> 1); | m will now contain number of bits set in the original m | popcnt in FreeBSD's sys/i386/i386/mp_machdep.c |
v -= ((v >> 1) & 0x55555555); | v will now contain number of bits set in the original v | popcnt comment in FreeBSD's sys/i386/i386/mp_machdep.c |
#define BITCOUNT(x) (((BX_(x)+(BX_(x)>>4)) & 0x0F0F0F0F) % 255) | macro to return number of bits in x (assumes 32bit integer) | BSD fortune |
n = ((n >> 1) & 0x55555555) | ((n << 1) & 0xaaaaaaaa); | reverse bits in a 32bit integer | BSD fortune |
popcnt(x ^ (x - 1)) & 31 | return first bit set in x, where popcnt returns number of bits set | Peter Wemm |
ffs using a lookup table | return first bit set | Colin Percival |
If you have any other cool bitwise tricks you know about, please e-mail them to John-Mark Gurney <jmg@funkthat.com>, and I will add them to the list.
A large collection of them can be found at Bit Twiddling Hacks.