henix / blog

some notes
0 stars 0 forks source link

binary hacks #24

Open henix opened 10 years ago

henix commented 10 years ago

get lsb: x & (-x)

remove lsb: x &= (x-1)

henix commented 10 years ago

http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2

v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
henix commented 10 years ago

define LOWBIT(x) ((x)&(-(x)))

henix commented 10 years ago
int msb(int x) {
    x |= (x >> 1);
    x |= (x >> 2);
    x |= (x >> 4);
    x |= (x >> 8);
    x |= (x >> 16);
    return x - (x >> 1);
}