在C语言中,如何计算无符号数的负数 [英] In C, how to get calculate the negative of an unsigned quantity

查看:817
本文介绍了在C语言中,如何计算无符号数的负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在K& R ANSI C书籍的A.7.4.5节(一元减法运算符)中指出:

In K&R ANSI C book, section A.7.4.5 (Unary Minus Operator) it is stated:

...无符号数量的负数是通过从提升类型的最大值中减去提升值并加一个得出的; ...

... The negative of an unsigned quantity is computed by subtracting the promoted value from the largest value of the promoted type and adding one; ...

这是如何精确计算的?您能否举一个简短的C示例?

How exactly is this calculated? Could you give a short C example?

我不知道这怎么会产生200u的负数:从任何整数类型(有符号或无符号)的最大值减去200并加1不会得到-200.

I don't see how this could yield the negative of, say, 200u: subtracting 200 from a max value of any integral type (signed or unsigned) and adding 1 does not result in -200.

我知道一元减号的作用-问题是我看不到根据描述如何计算结果.

I know what the Unary minus does - the problem is that I don't see how the result is calculated according to the description.

推荐答案

很明显,您在引用的描述中漏了 unsigned 一词.在这种情况下,这是关键词.在C语言中,无符号数量的负数"仍然是无符号的,这意味着它并不是真正的负数.根据定义,无符号值永远不能为负.它们始终为正或0.C中无符号值的算术是模运算或简单来说,当您对它们执行算术运算时,无符号数"会环绕".一元否定也不例外.当n是无符号的时计算-n与计算0 - n没什么不同.如果nunsigned int并且其值是200,则预期结果不是-200,而是UINT_MAX - 200 + 1,这正是引用所告诉的内容.

Apparently you missed the word unsigned in the description you quoted. This is the key word in this case. In C language the "negative" of an unsigned quantity is still unsigned, meaning that it is not really negative. Unsigned values can't ever be negative, by definition. They are always positive or 0. Arithmetic of unsigned values in C is modulo arithmetic or, in simple words, unsigned quantities "wrap around" when you perform arithmetical operations on them. Unary negation is not an exception. Calculating -n when n is unsigned is no different from calculating 0 - n. If n is unsigned int and its value is 200 the expected result is not -200, but rather UINT_MAX - 200 + 1, which is exactly what the quote is telling you.

这篇关于在C语言中,如何计算无符号数的负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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