erotavlas
erotavlas

Reputation: 4493

How can I calculate powers of 2 using left shift operator for large powers?

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.

Upvotes: 9

Views: 21731

Answers (3)

erotavlas
erotavlas

Reputation: 4493

I found a solution, instead of long (Int64) which goes to maximum of power 63, I used BigInteger from System.Numerics

    public static BigInteger TwoPowX(int power)
    {
        return ((BigInteger)1 << power);
    }

and then usage

    BigInteger test = Utility.TwoPowX(96);

yields the correct value for powers greater than 63 (in this example - power of 96)

{79228162514264337593543950336}

Upvotes: 1

Abir
Abir

Reputation: 31

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;

Upvotes: 3

Jakub Lortz
Jakub Lortz

Reputation: 14894

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);
}

Upvotes: 6

Related Questions