Wednesday, May 23, 2007

Bit Hacks

I would like to present some of the interesting Bit Hacks..

Determining if an integer is a power of 2

unsigned int v; // we want to see if v is a power of 2
bool f; // the result goes here

f = (v & (v - 1)) == 0;
Note that 0 is incorrectly considered a power of 2 here. To remedy this, use:
f = !(v & (v - 1)) && v;

Compute the integer absolute value (abs) without branching

int v;      // we want to find the absolute value of v
int r; // the result goes here
int const mask = v >> sizeof(int) * CHAR_BIT - 1;

r = (v + mask) ^ mask;

Swapping values with XOR

#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) This is an old trick to exchange the values of the variables a and b without using extra space for a temporary variable.

On January 20, 2005, Iain A. Fleming pointed out that the macro above doesn't work when you swap with the same memory location, such as SWAP(a[i], a[j]) with i == j. So if that may occur, consider defining the macro as (((a) == (b)) || (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))).

For many other bithacks click here

Friday, May 18, 2007

My First Blog

I had blogs before they were too technical. So i decided to have a new one with some semi-technical stuffs so that people from every domain can enjoy. I am presently doing my Project at Intel Technologies.. Bangalore..
I work in the Technology Manufacturing Group (TMG)..I am in the Control Systems and Engineering(CSE) Team presently working with Vidya Sridhar. I hope the life here gonna be great and interesting. I will come up with interesting things. Keep reading and have a great time.