最有效的便携式溢出检测?
与 C、C++ 和 D 等金属语言类似,检测无符号 64 位溢出的最有效、合理可移植的方式是什么(即不使用汇编程序,尽管您可能假设二进制补码算术和环绕行为)乘法中的整数?
In close to the metal languages like C, C++ and D, what's the most efficient reasonably portable way (i.e. w/o using assembler, though you may assume two's complement arithmetic and wrap-around behavior) to detect overflow of an unsigned 64-bit integer on multiplication?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过将无符号类型可表示的最大值除以被乘数之一,可以提前检测溢出;如果结果小于另一个被乘数,则将它们相乘将导致值超出无符号类型的范围。
例如,在 C++ 中(使用 C++0x 精确宽度数值类型):
在 C 中,您可以使用
uint64_t
作为类型,使用UINT64_MAX
作为最大值。或者,如果您只关心类型至少 64 位宽,而不一定完全 64 位宽,则可以使用unsigned long long
和ULLONG_MAX
。You can detect overflow in advance by dividing the maximum value representable by the unsigned type by one of the multiplicands; if the result is less than the other multiplicand, then multiplying them would result in a value exceeding the range of the unsigned type.
For example, in C++ (using the C++0x exact-width numeric types):
In C, you can use
uint64_t
for the type andUINT64_MAX
for the maximum value. Or, if you only care that the type is at least 64 bits wide and not necessarily exactly 64 bits wide, you can useunsigned long long
andULLONG_MAX
.这个几乎重复的问题中有一些答案。 这个答案应该适用于C,C++和其他类似语言:
或者这个答案 执行乘法,然后将结果除以其中一个参数,看看它是否等于另一个:
There are a few answers in this almost duplicate question. This answer should work in C, C++, and other similar languages:
Or this answer which performs the multiplication and then divides the result by one of the arguments to see if it equals the other:
可能有更有效的方法,但这是一种简单且便携的方法:
There are probably more efficient methods but this is an easy and portable way to do it: