允许签署整数溢出C / C ++ [英] Allowing signed integer overflows in C/C++

查看:91
本文介绍了允许签署整数溢出C / C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的希望的符号整数溢出,当他们变得过于庞大。我如何做到这一点,而无需使用下一个最大的数据类型(或当我已经在int128_t)?

I want signed integers to overflow when they become too big. How do I achieve that without using the next biggest datatype (or when I am already at int128_t)?

例如使用8位整数,19 * 12是常用260,但我想要的结果 1 11 10 01 00 与第9位切断,从而-27。

For example using 8bit integers 19*12 is commonly 260, but I want the result 1 11 10 01 00 with the 9th bit cut off, thus -27.

推荐答案

符号溢出是未定义的C和的这是真正的

Signed overflow is undefined in C, and that's for real.

一个解决方法如下:

signed_result = (unsigned int)one_argument + (unsigned int)other_argument;

以上解决方案涉及从在最终转化实现定义的符号 INT ,但不发生未定义行为。对于大多数编译平台的实现定义选择,其结果正是您所期望的补码的结果。

The above solution involves implementation-defined behavior in the final conversion from unsigned to int but do not invoke undefined behavior. With most compilation platforms' implementation-defined choices, the result is exactly the two's complement result that you expect.

最后,为众多平台上,实现定义选项强制编译器给你一次一个优化的编译器行为您预计会编译高于code到明显的汇编指令。

Finally, an optimizing compiler for one of the numerous platforms on which implementation-defined choices force the compiler to give you the behavior you expect will compile the above code to the obvious assembly instruction.

另外,如果你正在使用gcc,那么选择 -fwrapv / -fno严格溢可正是你想要的。他们提供关于签署溢出环绕标准的额外保障。我不知道对两者之间的区别。

Alternately, if you are using gcc, then the options -fwrapv/-fno-strict-overflow may be exactly what you want. They provide an additional guarantee with respect to the standard that signed overflows wrap around. I'm not sure about the difference between the two.

这篇关于允许签署整数溢出C / C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆