NSUInteger为什么/如何返回负数?

Ale*_*ray 5 primitive xcode casting objective-c clang

有一个单独的无符号类型NSUInteger什么意义,即如果没有保证(甚至,似乎是一个机会),你可以假设,押注你的底价,或者让自己哭泣 - 顾名思义 -一个固有的非负的结果.

NSUInteger normal = 5;
NSUInteger freaky = normal - 55;
NSLog(@"%ld, %ld", normal, freaky);
Run Code Online (Sandbox Code Playgroud)

NSLOG 5, -50

当然,我可以向后弯腰试图获得零或某种标准化值......

NSUInteger nonNeg = (((normal - 55) >= 0) ? (normal - 55) : 0);
Run Code Online (Sandbox Code Playgroud)

PARRALELUNIVERSELOG 5, -50

但是在这里,编译器抱怨......理所当然地comparison of unsigned expression >= 0 is always true- 而且它就是,我不想要/期望的答案.有人拍我的脸,给我一杯饮料,告诉我它是哪一年......或者更好 ......如何制作 - 你知道 - 不要这样做.

idz*_*idz 8

%ld告诉NSLog它将其打印为有符号整数.试试%lu.

请参阅维基百科上的2's Complement,了解位级别的内容.

这里发生的是减法导致无符号整数表示环绕.为防止这种情况,您需要在进行减法之前进行检查.

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
}
Run Code Online (Sandbox Code Playgroud)