C 语言中的无符号和有符号除法

发布于 2025-01-08 05:01:21 字数 309 浏览 1 评论 0原文

在我的程序中,两个变量被声明为有符号长整型(比方说 32 位机器上的 X 和 Y),并将这些变量除以其他变量(X/Y)。

最终值被分配给一个无符号长变量(假设为Z)。我不确定这是正确还是错误的分配。我只是在调试某人编写的代码。我猜这可能会导致溢出或未定义状态。

在下面四种情况下会发生什么,

Z =+X/+Y  
Z =+X/-Y  
Z =-X/+Y  
Z =-X/-Y

我知道 %u 表示无符号,%d 表示整数。我的问题是在上述四种情况下 Z 中将存储什么值。

任何帮助将不胜感激。

In my program two variables are declared as signed long (let say X and Y on 32 bit machine) and these divided one by other(X/Y).

The final value is assigned to a unsigned long variable(Let say Z). I am not sure whether this is right or wrong assignment. I am just debugging a code that was written by some one. I guess this may lead to overflow or undefined state.

What happens in below four scenarios,

Z =+X/+Y  
Z =+X/-Y  
Z =-X/+Y  
Z =-X/-Y

I know that %u for unsigned and %d for integer. My question is regarding what value would be stored in Z in the above four scenarios.

Any help would be greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

濫情▎り 2025-01-15 05:01:21

如果您的变量已签名,则一切都很好。如果您得到负除法结果,之后可能会发生(不需要的?)转换。

使用包含无符号值的表达式会更加痛苦,例如

(1U-2)/10

会产生意外的结果。

If your variables are signed, all is fine. Perhaps there is a (unwanted?) conversion afterwards if you gert a negative division result.

Working with expressions containing unsigned values is more painful, e.g.

(1U-2)/10

gives unexpected results.

苍白女子 2025-01-15 05:01:21

如果除法结果为负,你会得到垃圾。

例如:

unsigned z;
int a = 10;
int b = -2;
z = a/b;

那么z == 4294967291

You'll get garbage if result of division is negative.

For example:

unsigned z;
int a = 10;
int b = -2;
z = a/b;

then z == 4294967291.

梓梦 2025-01-15 05:01:21

Z 将存储整数除法的值,但由于 Z 是无符号的,所有值都将为正,因此符号位不会按原样处理,而是作为数字的一部分,并且也不会进行补码转换。例如,如果 unsigned int 是 32 位宽:

X = 1, Y = 1 -> Z = 1
X = -1, Y = 1 -> Z = 4294967295 = 0xFFFFFFFF (this would be -1 -two's complement- if Z was signed)

Z would store the value of the integer division, but as Z is unsigned, all values will be positive, and thus the sign bit will not be processed as such, but as part of the number, and also there will be no two's complement conversion. For example, if unsigned int is 32-bit wide:

X = 1, Y = 1 -> Z = 1
X = -1, Y = 1 -> Z = 4294967295 = 0xFFFFFFFF (this would be -1 -two's complement- if Z was signed)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文