如何在C中快速找到2 ^ x。如果你们有任何想法,请帮忙。
How to find 2^x quickly in C. If you guys have any idea please help.
最满意答案
向左移位时,对于每个位置移位,这将数字乘以2,与将左移十进制数字乘以10相同。
使用<<运算符,如下所示:
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;依此类推,直到你达到1 << 30 。 如果你使用一个有符号的32位整数,那么1 << 31会给你-2147483648,因为有二进制补码。 如果你想要比使用long long unsigned int或uint64_t (64位整数)更高。 或者,如果您的平台支持它: uint128_t 。
如果你想要更高,你需要推出自己的“大整数”代码。 请注意,某些平台和编译器带有128位整数类型,但运行时性能各不相同:它们可能需要可执行128位操作的处理器,或者可能会将其分解为两个64位操作。
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.
更多推荐
发布评论