美文网首页
int与NSInteger一些知识总结

int与NSInteger一些知识总结

作者: Patrick_QiWei | 来源:发表于2020-03-06 09:55 被阅读0次

    各种int所占字节

    类型 所占字节数
    short int 2个字节
    int 4个字节
    long 32位:4个字节;64位:8个字节
    long long 8个字节
    //
    //  main.m
    //  commandForPractice
    //
    //  Created by patrick on 2019/11/6.
    //  Copyright © 2019 patrick. All rights reserved.
    //
    #import <Foundation/Foundation.h>
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            short num = 10;
            int num2 = 10;
            long num3 = 10;
            long long num4 = 10;
            NSLog(@"num == %lu, num2 == %lu, num3 == %lu, num4 == %lu", sizeof(num), sizeof(num2), sizeof(num3), sizeof(num4));
        }
        return 0;
    }
    
    // 控制台输出
    2020-03-06 08:22:44.044774+0800 commandForPractice[9838:691745] short == 2, int == 4, long == 8, long long == 8
    

    因为这边用的操作系统是64位操作系统,所以说long类型的也占8个字节,但是如果是32位操作系统的话就会显示占4个字节

    知道了各种int所占的字节后,我们又知道1字节(byte) == 8比特(bit),所以可以换算出各个int的取值范围。这边long就以8个字节换算,如果long是占4个字节的话取值范围就与int相同

    类型 取值范围
    short -32768~32767(-2^15 ~ 2^15-1)
    int -2147483648~2147483647(-2^31 ~ 2^31-1)
    long -9223372036854775808 ~ 9223372036854775807(-2^63 ~ 2^63-1)
    long long -9223372036854775808 ~ 9223372036854775807(-2^63 ~ 2^63-1)

    OC中的NSInteger

    有时候看OC的代码的时候,一直会看到数据类型NSInteger,那它倒是是个什么呢?以下是其代码的定义:

    #if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
    typedef long NSInteger;
    typedef unsigned long NSUInteger;
    #else
    typedef int NSInteger;
    typedef unsigned int NSUInteger;
    #endif
    

    objective-c里,苹果的官方文档中总是推荐用NSInteger

    它和int有什么区别呢,stackoverflow这帮大神给了答案。

    NSInteger是一个封装,它会识别当前操作系统的位数,自动返回最大的类型。当你不知道你的操作系统是什么类型的时候,你通常会想要使用NSInteger,所以或许你想要你的int类型范围尽可能的大,用NSInteger,32位系统NSInteger是一个int,即32位,但当时64位系统时,NSInteger便是64位的。——所以就是一般推荐用NSInteger的

    参考:
    https://www.jianshu.com/p/6cf652250905

    相关文章

      网友评论

          本文标题:int与NSInteger一些知识总结

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