当我分配一个负值一个unsigned int会发生什么? [英] What happens when I assign a negative value to an unsigned int?

查看:454
本文介绍了当我分配一个负值一个unsigned int会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/50605/signed-to-unsigned-conversion-in-c-is-it-always-safe\">signed在C无符号的转换 - 是它总是安全

比方说,我宣布unsigned int类型的变量: unsigned int类型X = -1;

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

现在-1补(假设32位机)是0xFFFFFFFF。
现在,当我分配了此值X,做了价值得到为0x7FFFFFFF分配到X?

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?

如果真是这样,那么的printf(%D,X);将印刷的为0x7FFFFFFF十进制等效,对不对?但是,很显然这是不会发生,因为这会打印值为-1。缺少什么我在这里?

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?

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

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

推荐答案

%D格式是(signed)​​int的值。如果用一个无符号值使用它,它可以打印比实际值以外的东西。使用%U来看看实际值,或%X 看到它在十六进制。

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.

在声明

unsigned int x = -1;

恩pression 1 是int类型,并具有值-1。初始化转换从int到unsigned int类型此值。有符号到无符号转换的规则说,价值减少模 UINT_MAX + 1 ,所以 1 将转换为 UINT_MAX (这可能是为0xffffffff 4294967295 如果 unsigned int类型为32位)。

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).

您只需不能的负值分配给无符号类型的对象。它的分配前的任何这样的值将被转换为无符号的类型,其结果将总是> = 0

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.

这篇关于当我分配一个负值一个unsigned int会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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