Absolute value of NSInteger

后端 未结 3 1353
走了就别回头了
走了就别回头了 2021-02-11 15:15

Referring to Convert to absolute value in Objective-C I\'m wondering if there are functions for NS typedefed types. Or is abs(NSInteger) okay? Is it architecture-sa

相关标签:
3条回答
  • 2021-02-11 15:38

    Use ABS() macro, which is defined in NSObjCRuntime.h, it is architecture-safe.

    0 讨论(0)
  • 2021-02-11 15:42

    You can use Foundation’s ABS() macro:

    NSInteger a = 5;
    NSInteger b = -5;
    NSLog(@"%ld %ld", ABS(a), ABS(b));
    
    0 讨论(0)
  • 2021-02-11 15:50

    While the two posted answers are absolutely correct about using the ABS() macro, it should certainly be noted that NSIntegerMin, whose true absolute value can not be represented as an NSInteger returns itself when the ABS() function is called.

    Presuming a 64-bit system:

    NSLog(@"ld", ABS(NSIntegerMin)); 
    // prints: -9223372036854775808
    
    NSLog(@"%ld", ABS(NSIntegerMin + 1)); 
    // prints: 9223372036854775807, which == NSIntegerMax
    

    The same results will happen on a 32-bit system, but the numbers will be +2147483647 and -2147483648

    0 讨论(0)
提交回复
热议问题