Sunday, September 14, 2008

Power of 2: 2^n

It is good to know that we use bitwise operator (<<) in order to calculate power of 2 (2^n). In a one byte system, we represent 1 as 00000001 and when we shift right-most one to left by one, that is 00000010 means 2.

If go on to shift, we will see that it just takes one more power of 2. So, basically we can say that 1 << n (must have no space between) notation calculates the power of n as 2^n. A simple function implementation in C is like:
unsigned int power(unsigned int pow) {
int result=1 << pow;
return result;
}

0 comments: