当我将负值赋给 unsigned int 时会发生什么?

发布于 2024-11-30 17:57:42 字数 496 浏览 1 评论 0原文

可能的重复:
C 中的有符号到无符号转换 - 它总是安全吗?

假设我声明了一个 unsigned int 类型的变量: unsigned int x = -1;

现在 -1 的二进制补码(假设 32 位机器)是 0xFFFFFFFF。 现在,当我将此值赋给 x 时,值 0x7FFFFFFF 是否被赋给了 x?

如果是这样,则 printf("%d",x);会打印 0x7FFFFFFF 的十进制等值,对吧?但是,显然这不会发生,因为打印的值为 -1。我在这里缺少什么?

编辑:我知道我们可以使用 %u 格式说明符来打印无符号值。 但这无助于回答上面的问题。

Possible Duplicate:
signed to unsigned conversion in C - is it always safe?

Let's say I declare a variable of type unsigned int : unsigned int x = -1;

Now -1 in two's complement (assuming 32 bit machine) is 0xFFFFFFFF.
Now when I assigned this value to x, did the value 0x7FFFFFFF get assigned to x?

If it were so, then printf ("%d",x); would have printed the decimal equivalent of 0x7FFFFFFF, right? But, clearly this isn't happening, as the value that gets printed is -1. What am I missing here?

Edit: I know that we can use the %u format specifier to print unsigned values.
But that doesn't help answer the question above.

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

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

发布评论

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

评论(3

挖鼻大婶 2024-12-07 17:57:42

"%d" 格式适用于(有符号)int 值。如果将其与无符号值一起使用,它可能会打印实际值以外的内容。使用 "%u" 查看实际值,或使用 %x 查看十六进制值。

在声明中,

unsigned int x = -1;

表达式-1 的类型为int,值为-1。初始化器将此值从 int 转换为 unsigned int。有符号到无符号转换的规则规定,该值会以 UINT_MAX + 1 为模减少,因此 -1 将转换为 UINT_MAX(其中如果 unsigned int 是 32 位,则可能是 0xffffffff4294967295)。

您只是不能将负值赋给无符号类型的对象。任何此类值在分配之前都会被转换为无符号类型,并且结果将始终 >= 0。

The "%d" format is for (signed) int values. If you use it with an unsigned value, it could print something other than the actual value. Use "%u" to see the actual value, or %x to see it in hexadecimal.

In the declaration

unsigned int x = -1;

the expression -1 is of type int, and has the value -1. The initializer converts this value from int to unsigned int. The rules for signed-to-unsigned conversion say that the value is reduced modulo UINT_MAX + 1, so -1 will convert to UINT_MAX (which is probably 0xffffffff or 4294967295 if unsigned int is 32 bits).

You simply cannot assign a negative value to an object of an unsigned type. Any such value will be converted to the unsigned type before it's assigned, and the result will always be >= 0.

对你的占有欲 2024-12-07 17:57:42

使用 %u 而不是 %d 来打印无符号值。然后你应该看到 0xFFFFFFFF。

Use %u instead of %d in order to print unsigned values. Then you should see 0xFFFFFFFF.

请持续率性 2024-12-07 17:57:42

发生的情况是,您首先将值转换为 unsigned int,将 0xffffffff 分配给 x。然后使用 printf("%d\n") 将值转换回有符号 int,仍保留 0xffffffff 值。因此打印-1。

What is happening is that you convert the value first to unsigned int, assigning 0xffffffff to x. Then using printf("%d\n") you will convert the value back to signed int still keeping the value of 0xffffffff. Thus printing -1.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文