Main BLOGGER
Google
WWW THIS BLOG
Thursday, March 24, 2005
 
Play with Bit
A good one at http://graphics.stanford.edu/~seander/bithacks.html



It is very useful. Some common questions like:
Many tricks are based on
1. sign = v >> (sizeof(int) * 8 - 1); // if v < v =" ~v" v="1100"> 1000

(1) abs()
cwd //get the sign of [ax] into dx: -1 when <0 ax =" [ax]">0 else -([ax])-1
sub ax,dx // ax = [ax] when >0 else -([ax])-1-(-1);

(2) power of 2
f = !(v & (v - 1)) && v;

(3) Counting bit set
Brian Kernighan's way
unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{
v &= v - 1; // clear the least significant bit set
}
parallel sideway addition
unsigned int v; // count bits set in this (32-bit value)
unsigned int c; // store the total here
const int S[] = {1, 2, 4, 8, 16}; // Magic Binary Numbers
const int B[] = {0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF};

c = v;
c = ((c >> S[0]) & B[0]) + (c&B[0]);
//add adjacent one bits 1,1->10 1,0->01 0,1->01 0,0->00
c = ((c >> S[1]) & B[1]) + (c&B[1]); //
//add adjacent two bits 00,00->0000 00,01->0001 01,00->0001 etc...
c = ((c >> S[2]) & B[2]) + (c&B[2]);
//add adjacent four bits 0000,0000->00000000, etc
c = ((c >> S[3]) & B[3]) + (c&B[3]);
//add adjacent eight bits
c = ((c >> S[4]) & B[4]) + (c&B[4]);
//add adjacent sixteen bits


(4) increament without "+" or "-"
(~a) * (~0)
[equiv] (-a-1) * (-1) = a+1
-0 = ~0 + 1 ==> ~0 = -1

(5) Modulo 3 without equation X-X/3
Given x = v>>2 we have
v= 4*x + v&3 = 3*x + x + v&3
with v mod 3 == (3*x + x + v&3) mod 3 == (x+v&3) mod 3 == (v>>2+v&3) mod 3
so we have
int Modulo3(const int x)
{
int v = x;
while (v > 3)v = v>>2 + v&3;
if (v>2) v=v-3;
return v;
}
the same idea fits Modulo 5
int Modulo5(const int x)
{
int v = x;
while (v>15)
{
v = v >>4 + v&15;
// given x = v>>4;
// v mod 5 == (16*x+v&15) mod 5
// == (15*x + x + v&15) mod 5
// == (x+v&15) mod 5 == ( v>>4+v&15) mod 5
}
while (v>4)
{
v = v - 5;
}
return v;
}



<< Home

Powered by Blogger

Google
WWW THIS BLOG