c - 从算术运算中获取溢出

标签 c math integer-overflow

做数学运算时,如何得到溢出的部分?

例如,假设 32 位整数:

unsigned int a = 0Xffffffff;
unsigned int b = 0xffffffff;
unsigned int c = a + b;

在这种情况下,c0xfffffffe,但答案应该是 0x1fffffffe。如何获得溢出的 1?

我怎样才能对乘法做同样的事情?我可以将两个大数相乘,只得到溢出的部分吗?

bigint 库如何管理它?

最佳答案

@Warning 不可携带@

  1. 使用 https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html

示例:https://godbolt.org/z/NcyNzR

#include <stdio.h> 
int main(void)
{
    unsigned int res;

    if(__builtin_uadd_overflow(0Xffffffff, 0Xffffffff, &res))
    {
        printf("Overflowed\n");
    }
    printf("Result: 0x%x\n", res);
}
  1. 使用内联汇编读取进位标志

关于c - 从算术运算中获取溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60358013/

相关文章:

C - 当循环条件为 ptr != NULL 时出现段错误

javascript - AudioContext:将音量增加 x 分贝

c++ - 我如何处理算术溢出?

c - 海湾合作委员会 C 错误 : expected ')' before numeric constant

c - 用time.h测量时间?

c++ - 如何判断我使用的库、dll 和函数是否是 C++ Native

c# - 将非常大的数字转换为以 10 为基数的字符串

计算 N 组总成本的算法

c++ - 如何检测无符号整数溢出?

c - 如何检查数字是否溢出 'int'