溢流公司
我有一个疑问,
当两个16位值与最大值相加时,在16位机器上会出现溢出吗?
我将详细
unsigned short a;
unsigned short b;
unsigned long c;
c=(unsigned long)(a+b);
说明关于 16 位处理器,累加器将具有 16 位大小。 上面的语句会不会出现溢出? 请澄清。
I have a doubt
When two 16 bit values are added with max values, will there be overflow in the 16 bit machines?
I will elaborate
unsigned short a;
unsigned short b;
unsigned long c;
c=(unsigned long)(a+b);
Talking about 16 bit processers the accumulator will be of 16 bit size. Will there be an overflow in the above statement? Please clarify.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据这些定义并假设
unsigned Short
== 16 位且int
== 16 位且unsigned long
== 32 位(请注意,大小int
很重要):这两个语句将执行不同的操作:
第一个语句(您显示的那个语句)将首先将数字添加为无符号短裤,丢弃任何溢出 - 和 然后扩展为无符号长整型。 这可能就是你问的原因。 第二个将
a
转换为 unsigned long,然后将两个数字相加,在进行加法之前将b
扩展为 unsigned long。您也可以这样做:
但这是不必要的,因为计算中存在一个 unsigned long 会导致另一个自动从短大小提升为长大小。
因此:
所有这些都取决于您的特定编译器及其变量的大小。 它具体取决于编译器上
int
的大小,因为在计算过程中所有值都会自动提升为int
或unsigned int
。 您提到了具有 16 位累加器的硬件,C 编译器通常(但并非总是)使用本机寄存器大小作为int
的大小,这就是为什么我假设int
作为 16 位。With these definitions and assuming
unsigned short
== 16 bit andint
== 16 bit andunsigned long
== 32 bit (note that the size ofint
is important):These two statements will do different things:
The first one -- the one you showed -- will first add the numbers as unsigned shorts, discarding any overflow -- and then expand to an unsigned long. This may be why you're asking. The second will cast
a
to an unsigned long, then add the two numbers, expandingb
to an unsigned long as well before doing the addition.You could also do this:
but it's unnecessary as the presence of one unsigned long in the calculation will cause the other to be automatically promoted from short to long size.
Thus:
All of this depends on your specific compiler and on the size of its variables. It depends specifically on the size of an
int
on your compiler, as all values are automatically promoted toint
orunsigned int
during calculations. You mentioned hardware with 16 bit accumulators, and C compilers will typically (but not always) use the native register size as the size ofint
, which is why I assumed anint
as 16 bits.是的,会有溢出。 子表达式 a + b 的类型为short,只有在对其求值后,结果才会转换为long。 这样做:
这将导致 a 在加法发生之前被转换为 long,而这反过来又会导致 b 也被转换为 long。 因此,两个长整型相加,并且不会发生溢出。
Yes, there will be an overflow. The subexpression a + b has type short, and only after it has been evaluated is the result cast to a long. Do this:
This will cause a to be cast to a long before the addition takes place, and this in turn will cause b to be cast to a long as well. Hence the addition of two longs takes place, and no overflow will occur.