按位饱和除了在C(HW) [英] Bitwise saturated addition in C (HW)

查看:198
本文介绍了按位饱和除了在C(HW)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的分配,我无法弄清楚如何实现这一点。我必须做出一个函数SADD(INT X,int y)对返回加在一起,除非它溢出的数字(当时只返回最大可能INT)。我已经能够拿出涉及铸造和​​条件语句的一些解决方案,但那些没有在解决方案使。只有运营商〜! ^ + LT;< >>&安培;和|

I'm working on an assignment and I can't figure out how to implement this. I have to make a function sadd(int x, int y) that returns the numbers added together unless it overflows (then just return the max possible int). I've been able to come up with some solutions involving casting and conditional statements, but those aren't allowed in the solution. Only the operators ~ ! ^ + << >> & and |.

推荐答案

有关除了符号数,如果添加符号相同的两个号码,并得到了不同的符号结果溢出发生。由于所涉及的范围中,这是不可能产生添加的符号不同的两个数字时溢出。

For addition of signed numbers, overflow has happened if you add two numbers of the same sign and get a result with a different sign. Because of the ranges involved, it is impossible to generate overflow when adding two numbers of different signs.

那么,你能做的就是 - 看符号位只(最显著之一补) - 用异或去原来的两个号是否注册不同,补充说让你有 0',如果他们是不同的,1为相同

So, what you can do is — watching the sign bit only (the most significant one in two's complement) — use exclusive OR to get to whether the two original numbers differed in sign, complement that so that you've got '0' if they were different, '1' for the same.

您就可以使用专属或结果与一个输入。这会给'0',如果他们是一样的,'1',如果他们是不同的。

You can then use exclusive OR on the result versus one of the inputs. That'll give '0' if they were the same, '1' if they were different.

和这两个结果合力得到全面'1',如果两个输入信号相同,但结果却是不同的,'0',否则。

And those two results together to get an overall '1' if the two inputs were the same but the result was different, '0' otherwise.

您可以再使用的变化和手术室的组合,以填补该值的整个整数。假如你在一个32位整数是,刚刚成立的最低31位,以获得最高的价值正整数。那么,什么可以做的是一个类似对其中一个输入符号移位和手术室套。异或结果。这反而会给予最低值整数如果输入均为阴性。

You can then use a combination of shifts and ORs to fill an entire integer with that value. Supposing you're in a 32 bit integer, just set the lowest 31 bits to get the highest value positive integer. What you can then do is a similar sets of shifts and ORs on the sign bit of either of the inputs. Exclusive OR the results. That'll instead give the lowest value integer if the inputs were negative.

编辑:哦,使用是否有溢出,扩大填补整型的位值,选择什么样的价值与结果安定它返回如果有溢出,你会回来,补充它和安定它与正常添加剂的结果,那么或门(或增加),两人在一起。

oh, and use the bit value of whether there was overflow, extended out to fill the int, to select what value to return by anding it with the result you would return if there were overflow, complementing it and anding it with the normal additive result, then oring (or adding) the two together.

preSTO:所有二元逻辑,没有条件语句。我假设,因为它的功课,你不希望实际code?

Presto: all binary logic, no conditionals. I assume, because it's homework, that you don't want actual code?

这篇关于按位饱和除了在C(HW)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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