Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to calculate integer powers of 2 in C#?

Tags:

c#

integer

I'm sure this isn't as difficult as I'm making it out to be.

Would like to use something equivalent to Math.Pow(double, double) but outputting an integer. I'm concerned about roundoff errors with the floating points.

The best I can come up with is:

uint myPower = 12;
uint myPowerOfTwo = (uint)Math.Pow(2.0, (double)myPower);

I thought of this:

uint myPowerOfTwo = 1 << myPower;    // doesn't work

but I get the error that operator "<<" cannot be used with operands of type int or and uint.

Any suggestions? Thanks as always.

like image 257
John Avatar asked Mar 31 '11 22:03

John


1 Answers

you will have to use a signed integer for the second operand (right hand side) of the shift operator:

int myPower = 12;
int myPowerOfTwo = 1 << myPower;   

Of course you can cast the result to another numeric type such as uint:

uint myPowerOfTwo = (uint) (1 << myPower);   

From MSDN:

The left-shift operator (<<) shifts its first operand left by the number of bits specified by its second operand. The type of the second operand must be an int.

like image 198
BrokenGlass Avatar answered Oct 02 '22 07:10

BrokenGlass