今天我正在开发一个示例iOS应用程序,其中包含以下代码:
unsigned int uCount = 0;
int iJoke = -7;
uCount = uCount + iJoke;
Run Code Online (Sandbox Code Playgroud)
但是当我打印它时:
????????????????????????????????????????????????????????
? Format Specifier ? Print Statement ? Output ?
????????????????????????????????????????????????????????
? %d ? NSLog(@"%d",uCount); ? -7 ?
? %u ? NSLog(@"%u",uCount); ? 4294967289 ?
? %x ? NSLog(@"%x",uCount); ? fffffff9 ?
????????????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)
我预计%u的输出为7.
然后我用过:
unsigned int i = 0;
int j = -7;
i = i + abs(j);
Run Code Online (Sandbox Code Playgroud)
输出如下:
????????????????????????????????????????????????????
? Format Specifier ? Print Statement ? Output ?
????????????????????????????????????????????????????
? %d ? NSLog(@"%d",uCount); ? 7 ?
? %u ? NSLog(@"%u",uCount); ? 7 ?
? %x ? NSLog(@"%x",uCount); ? 7 ?
????????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)
虽然我的问题已得到解决abs(),但我很想知道为什么%u 4294967289在我的第一个案例中给出了结果.
请帮助,提前致谢.
此赋值将以模式表示-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 ]