快速找到2 ^ x的方法(Method to find 2^x quickly)

编程入门 行业动态 更新时间:2024-10-10 14:27:30
快速找到2 ^ x的方法(Method to find 2^x quickly)

如何在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.

更多推荐

本文发布于:2023-08-07 16:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465309.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:快速   方法   Method   find   quickly

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!