美文网首页
iOS开发中使用int的时候要小心点

iOS开发中使用int的时候要小心点

作者: 梁森的简书 | 来源:发表于2022-02-23 19:53 被阅读0次

看代码

NSNumber *number = @(2147483648);   // int能表示的最大数是2的31次方-1=2147483647(int占4个字节,总共32位,最高位是符号位不参与运算)
NSLog(@"%d", number.intValue);
NSLog(@"%lu", number.integerValue);

打印结果:

2022-02-23 19:25:33.504119+0800 0.test[53997:537254] -2147483648
2022-02-23 19:25:33.504284+0800 0.test[53997:537254] 2147483648

2147483648超出了int能表示的最大值,所以出现了负数。

int能表示的最大数是2的31次方-1=2147483647(int占4个字节,总共32位,最高位是符号位不参与运算)

为了更加保险,还是使用NSInteger更安全些。

#if __LP64__ || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif

相关文章

网友评论

      本文标题:iOS开发中使用int的时候要小心点

      本文链接:https://www.haomeiwen.com/subject/gzgrlrtx.html