power function by bitwise operations

Status
Not open for further replies.

maitrasagnik

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

QwertyManiac

Commander in Chief
Left shift operator is all you need.

To calculate 2^n, do:
Code:
2<<(n-1)

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

Some examples:
Code:
[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
 
Status
Not open for further replies.
Top Bottom