DIGIT-ARC read-only archive · snapshot: July 23, 2026

power function by bitwise operations

5 posts · originally from https://geek.digit.in/community/threads/power-function-by-bitwise-operations.78010/

M
maitrasagnik Original post #1
Jan 11, 2008 at 9:42 PM
can anyone tell me how to implement the function to calculate power of 2 with the help of bitwise operations.
QwertyManiac
Jan 11, 2008 at 9:49 PM
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
M
Jan 24, 2008 at 3:38 PM
Can the power of any other number calculated through it.
QwertyManiac
Jan 24, 2008 at 5:01 PM
No, it works out only for 2^n. For a^n there are other ways but none as efficient as this ..