简体   繁体   English

检测两个数字相加时是否发生无符号整数溢出

[英]Detecting if an unsigned integer overflow has occurred when adding two numbers

This is my implementation to detect if an unsigned int overflow has occurred when trying to add two numbers.这是我的实现,用于检测在尝试将两个数字相加时是否发生了 unsigned int 溢出。

The max value of unsigned int (UINT_MAX) on my system is 4294967295.我的系统上 unsigned int (UINT_MAX) 的最大值是 4294967295。

int check_addition_overflow(unsigned int a, unsigned int b) {
   if (a > 0 && b > (UINT_MAX - a)) {
    printf("overflow has occured\n");
   }
   return 0;
}

This seems to work with the values I've tried.这似乎适用于我尝试过的值。

Any rogue cases?有流氓案件吗? What do you think are the pros and cons?你认为有什么好处和坏处?

You could use 你可以用

if((a + b) < a)

The point is that if a + b is overflowing, the result will be trimmed and must be lower then a . 关键是如果a + b溢出,结果将被修剪,并且必须低于a

Consider the case with hypothetical bound range of 0 -> 9 (overflows at 10): 考虑假设边界范围为0 - > 9(溢出为10)的情况:

b can be 9 at the most. b最多可以是9。 For any value a such that a + b >= 10 , (a + 9) % 10 < a . 对于任何值a a + b >= 10(a + 9) % 10 < a
For any values a , b such that a + b < 10 , since b is not negative, a + b >= a . 对于任何值ab使得a + b < 10 ,因为b不是负的, a + b >= a

I believe OP was referring to carry-out, not overflow.我相信 OP 指的是结转,而不是溢出。 Overflow occurs when the addition/subtraction of two signed numbers doesn't fit into the number of type's bits size -1 (minus sign bit).当两个有符号数的加法/减法不适合类型位大小 -1(减符号位)的数量时,就会发生溢出。 For example, if an integer type has 32 bits, then adding 2147483647 (0x7FFFFFFF) and 1 gives us -2 (0x80000000).例如,如果整数类型有 32 位,那么将 2147483647 (0x7FFFFFFFF) 和 1 相加得到 -2 (0x80000000)。

So, the result fits into 32 bits and there is no carry-out.因此,结果适合 32 位并且没有进位。 The true result should be 2147483648, but this doesn't fit into 31 bits.真正的结果应该是 2147483648,但这不适合 31 位。 Cpu has no idea of signed/unsigned value, so it simply add bits together, where 0x7FFFFFFF + 1 = 0x80000000. Cpu 不知道有符号/无符号值,因此它只是将位加在一起,其中 0x7FFFFFFF + 1 = 0x80000000。 So the carry of bits #31 was added to bit #32 (1 + 0 = 1), which is actually a sign bit, changed result from + to -.因此,位#31 的进位被添加到位#32 (1 + 0 = 1),实际上是一个符号位,将结果从+ 更改为-。

Since the sign changed, the CPU would set the overflow flag to 1 and carry flag to 0.由于符号发生变化,CPU 会将溢出标志设置为 1,将进位标志设置为 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM