-3

今天我正在开发一个示例 iOS 应用程序,其中有如下代码:

unsigned int uCount = 0;
int iJoke = -7;
uCount = uCount + iJoke;

但是当我像这样打印它时:

╔══════════════════╦══════════════════════╦════════════╗
║ Format Specifier ║   Print Statement    ║   Output   ║
╠══════════════════╬══════════════════════╬════════════╣
║ %d               ║ NSLog(@"%d",uCount); ║ -7         ║
║ %u               ║ NSLog(@"%u",uCount); ║ 4294967289 ║
║ %x               ║ NSLog(@"%x",uCount); ║ fffffff9   ║
╚══════════════════╩══════════════════════╩════════════╝

我预计 %u 的输出为 7。

然后我像这样使用:

unsigned int i = 0;
int j = -7;
i = i + abs(j);

输出如下:

╔══════════════════╦══════════════════════╦════════╗
║ Format Specifier ║   Print Statement    ║ Output ║
╠══════════════════╬══════════════════════╬════════╣
║ %d               ║ NSLog(@"%d",uCount); ║      7 ║
║ %u               ║ NSLog(@"%u",uCount); ║      7 ║
║ %x               ║ NSLog(@"%x",uCount); ║      7 ║
╚══════════════════╩══════════════════════╩════════╝

虽然我的问题已解决abs(),但我很想知道为什么 %u4294967289在我的第一个案例中给出了结果。

请帮助,在此先感谢。

4

3 回答 3

6

此分配将以模式表示-7(以 2 的补码形式)分配给 unsigned int。这将是非常大的无符号值。

对于 32 位 int,这将是2^32 - 7 = 4294967289

标准如下所示

"If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]

于 2013-07-18T10:32:45.327 回答
0

ARM 将负数存储在二进制码中,因此在读取为无符号数时-7表示为。0xfffffff9

像这样表示负数的主要优点是添加有符号整数的指令与添加无符号整数的指令相同。

于 2013-07-18T10:31:32.743 回答
0

ijoke提升为无符号整数。在大多数编译器上,有符号位被扭曲以提供一个很大的正数。

当涉及无符号操作数时,转换规则更加复杂。

例如,假设 int 为 16 位,long 为 32 位。然后 -1L < 1U,因为 1U,它是一个 int,被提升为一个有符号的 long。

因为你似乎有一个 32 位的 int:

4294967296 - 7 = 4294967289

通常,大多数隐式转换是将“较窄”操作数转换为“较宽”操作数而不会丢失信息的转换。

于 2013-07-18T10:33:27.547 回答