I want to calculate powers of two without using Math.Pow because i want to avoid using double. So I need a whole integer value. I thought that I could just use the left shift operator but when my power goes past 30, it gives a negative number for power 31, and 1 for powers larger than 31.
My method looks like
public static long TwoPowX(int power)
{
return (1 << power);
}
Any ideas? Or alternative method?
EDIT: I need to go as high as power 96 maybe more.
2^96 = 79,228,162,514,264,337,593,543,950,336.
The literal 1
is an int, so the whole expression (1 << power)
will also be evaluated as int and overflow before being converted to long. Use 1L
instead.
public static long TwoPowX(int power)
{
return (1L << power);
}
What is the maximum power? Since int consists of 32 bits (31 bits for positive numbers) you get an overflow.
You can use long instead, but then keep in mind the maximum will be a power of 63.
return (long) 1 << power;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With