最有效的便携式溢出检测? [英] Most efficient portable overflow detection?

查看:122
本文介绍了最有效的便携式溢出检测?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/1815367/multiplication-of-large-numbers-how-to-catch-overflow\">multiplication大量,如何捕捉溢出

在接近金属的语言,如C,C ++和D,什么是最有效的合理的可移植的方法(即W / O使用汇编,尽管你可以假设补运算和环绕式的行为)来检测一个无符号的溢出乘法的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?

推荐答案

您可以通过将被乘数之一除以无符号类型的最大值再presentable检测溢出提前;如果结果是小于其他被乘数,然后乘以它们将导致超过无符号类型的范围内的值。

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.

例如,在C ++(用C ++ 0x中确切的宽度数值类型):

For example, in C++ (using the C++0x exact-width numeric types):

std::uint64_t left = 12;
std::uint64_t right = 42;

if (left != 0 && (std::numeric_limits<std::uint64_t>::max() / left) < right)
{
    // multiplication would exceed range of unsigned
}

在C,你可以使用 uint64_t中为最大值的类型和 UINT64_MAX 。或者,如果你只关心该类型的至少的64位宽,不一定的究竟的64位宽,可以使用无符号长长 ULLONG_MAX

In C, you can use uint64_t for the type and UINT64_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 use unsigned long long and ULLONG_MAX.

这篇关于最有效的便携式溢出检测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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