【问题标题】:How to implement power of two with logical shift in C?如何在 C 中通过逻辑移位实现二的幂?
【发布时间】:2016-04-17 01:28:08
【问题描述】:

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

逻辑转换可以作为有效的执行方式 无符号整数乘以或除以 2 的幂。 在有符号或无符号二进制数上左移 n 位具有 乘以 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

【问题讨论】:

  • 如您所见,左移位有其局限性。

标签: c logical-operators


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多