gpt4 book ai didi

c - 如何在 C 中通过逻辑移位实现 2 的幂?

转载 作者:太空宇宙 更新时间:2023-11-04 07:02:11 25 4
gpt4 key购买 nike

我只是从 C 开始,但我现在正在做的是一个简单的数学运算。我想要的是?我想要采用指数并返回二次幂的函数。我想使用逻辑移位运算符。 Wiki: Logical shifts

Logical shifts can be useful as efficient ways of performing multiplication or division of unsigned integers by powers of two. Shifting left by n bits on a signed or unsigned binary number has the effect of multiplying it by 2n.

但有一件事我无法理解,它不能正常处理大指数,例如 32。下面的代码中有详细信息。那么,如何在不使用数学库的情况下正确实现这样的功能呢?提前致谢。

long power_of_two_ext(int exp) {
exp = 32; // for testing purpose only

long retL = pow(2, exp);
printf("MATH pow() and long ---> %ld\n", retL);

long retL2 = 1 << exp;
printf("Shift bits left and long ---> %ld\n", retL2);

long long retL3 = 1 << exp;
printf("Left shift and long ---> %llu\n", retL3);
return retL;
}

MATH pow() and long ---> 4294967296
Left shift and long long ---> 1
Left shift and long ---> 1

最佳答案

1 << exp正在转移 int左边。只是因为您将结果分配给 longlong long , 并不意味着在该类型中计算表达式。正如所写,您的代码正在使用 int ,并且大概您正在运行 int 的机器上是 32 位。 [注意:向左移动大于或等于整数类型宽度的量是未定义的行为,因此您的代码的行为可能不一致]。

相反,使用正确类型的常量来确保您的表达式是正确的类型。

long retL2 = 1L << exp;
...
long long retL3 = 1LL << exp;

关于c - 如何在 C 中通过逻辑移位实现 2 的幂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36671725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com