2013-03-14 49 views

回答

4

使用格式说明符%d会导致您的无符号整数被解析,就像它被签名一样。

变化:

NSLog(@"Index: %d", index); 

到:

NSLog(@"Index: %u", index); 

,它会正确显示。

或者,只要使用NSInteger,如果您确实不需要无符号值。

+0

为什么匿名倒票,我想知道? – 2013-03-14 13:14:27

+0

我觉得因为你不在这一点。它不应该记录任何东西,因为-1小于0.至少这是我读的。 – nickdnk 2015-07-18 14:23:35

+0

@nickdnk:好的 - 谢谢 - 我现在看到代码有两个问题,并不能100%清楚OP所指的问题。 – 2015-07-18 14:46:15

1

问题是'整数'不知道任何有关它的签名/无符号特征。这只是一点点。 -1与值0xFFFFFFFF是不变的。

如果它是有符号/无符号的,那么类型'知道',并且在编译时正在发出正确的处理器指令。

NSUInteger index = -1; // effectively translates to index = 0xFFFFFFFF; (all bits set) 

if (index > 0) { // unsigned comparison - well, anything else than zero in unsigned comparison is bigger than zero 
    // so probably the JA (jump if above) asm instruction is emitted. 
    // if the index was NSInteger, JG will be emitted. 

    NSLog(@"Index: %d", index); // as others stated, you're now passing the bits of 'index' in way the NSLog treats them as signed integer 

}