5
4

2 回答 2

8

%ld tells NSLog to print it as a signed integer. Try %lu.

See 2's Complement on wikipedia for an explanation of what's going on at the bit level.

What is happening here is that subtraction is causing the unsigned integer representation to wrap-around. To protect against this you need to check before you do the subtraction.

NSUInteger x = 5; 
NSUInteger y = 55;

// If 0 makes sense in your case
NSUInteger result = (x >= y) ? (x - y) : 0; 

// If it should be an error
if(x < y)
{
    // Report error
}
于 2012-08-02T05:50:47.240 回答
0

真正的答案是如何解释这些位。当然,通过 2 的补码了解事情是如何在内部完成的很重要,但混淆似乎更多的是您在使用 %ld 时看到的是一个负数,并认为它与您在使用 % 时看到的正数有所不同鲁。两种情况都使用相同的位,这只是它们如何被解释的函数。如果您尝试将这些相同的位解释为字符序列,您会得到不同的结果。

于 2015-09-04T19:26:47.027 回答