# power function by bitwise  operations



## maitrasagnik (Jan 11, 2008)

can anyone tell me how to implement the function to calculate power of 2 with the help of bitwise operations.


----------



## QwertyManiac (Jan 11, 2008)

Left shift operator is all you need.

To calculate 2^n, do:

```
2<<(n-1)
```

n-1 cause 2<<0 is 2 itself.

Some examples:
	
	



```
[B](2 squared)[/B]
2<<1
4

[B](2 cubed)[/B]
2<<2
8

[B](2^4)[/B]
2<<3
16

[B](2^1)[/B]
2<<0
2

[B](2^11)[/B]
2<<10
2048
```


----------



## maitrasagnik (Jan 11, 2008)

thnxxx qm.


----------



## manubatham20 (Jan 24, 2008)

Can the power of any other number calculated through it.


----------



## QwertyManiac (Jan 24, 2008)

No, it works out only for 2^n. For a^n there are other ways but none as efficient as this ..


----------

