在整数乘法避免溢出其次师

编程入门 行业动态 更新时间:2024-10-23 22:22:21
本文介绍了在整数乘法避免溢出其次师的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个不可或缺的变量 A 和 B 和恒定取值 RESP。 D 。我需要计算的值(A * B)>> S RESP。 A * B / D 。问题是,乘法可能溢出,并最终的结果不会是即使 A * B / D 可以适合给定的整数类型正确。

I have two integral variables a and b and a constant s resp. d. I need to calculate the value of (a*b)>>s resp. a*b/d. The problem is that the multiplication may overflow and the final result will not be correct even though a*b/d could fit in the given integral type.

怎么可能得到有效解决?在简单的解决办法是扩大变量 A 或 B 来一个更大的整数类型,但也有可能不是一个大整型。有没有更好的办法来解决这个问题?

How could that be solved efficiently? The straightforward solution is to expand the variable a or b to a larger integral type, but there may not be a larger integral type. Is there any better way to solve the problem?

推荐答案

如果没有更大的类型,你要么需要找到一个大INT样式库,或用它处理手动,使用长乘法。

If there isn't a larger type, you will either need to find a big-int style library, or deal with it manually, using long multiplication.

例如,假设 A 和 B 是16位。然后你可以将其改写为 A =(1 <<;&LT; 8)*啊+铝和 B =(1 <<;&LT; 8)* BH + BL (其中所有的各个组件都是8位的数字)。然后,你知道,总的结果将是:

For instance, assume a and b are 16-bit. Then you can rewrite them as a = (1<<8)*aH + aL, and b = (1<<8)*bH + bL (where all the individual components are 8-bit numbers). Then you know that the overall result will be:

(a*b) = (1<<16)*aH*bH + (1<<8)*aH*bL + (1<<8)*aL*bH + aL*bL

每个这些4元件的适合的16位寄存器。您现在可以执行如在每个单独的组件的右移,小心处理适当进行。

Each of these 4 components will fit a 16-bit register. You can now perform e.g. right-shifts on each of the individual components, being careful to deal with carries appropriately.

更多推荐

在整数乘法避免溢出其次师

本文发布于:2023-11-30 05:30:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648884.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:乘法   整数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!