RBS RBS - 1 year ago 68
C Question

Method to find 2^x quickly

How to find 2^x quickly in C. If you guys have any idea please help.

Dai Dai
Answer Source

Bitshift to the left, this multiplies numbers by 2 for every place shift, in the same way that shifting decimal numbers to the left multiplies them by 10.

Use the << operator, like so:

int twoPowZero = 1; // any number^0 is 1
int twoPowOne  = 1 << 1; // this sets the '2' bit to '1'
int twoPowTwo  = 1 << 2;
int twoPowFive = 1 << 5;
int twoPowTen  = 1 << 10;

and so on until you get to 1 << 30. If you're using a signed 32-bit integer then 1 << 31 will give you -2147483648 because of two's complement. If you want to go higher than use long long unsigned int or uint64_t (64-bit integer). Or if your platform supports it: uint128_t.

If you want to go even higher, you'll need to roll your own "big integer" code. Note that some platforms and compilers come with a 128-bit integer type, but runtime performance varies: they may require a processor that can perform 128-bit operations, or they might break it down into two 64-bit operations.