Skip to content

Instantly share code, notes, and snippets.

@AgoniNemo
Created December 5, 2017 07:36

Revisions

  1. AgoniNemo created this gist Dec 5, 2017.
    99 changes: 99 additions & 0 deletions iOS中的字节知识.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,99 @@

    字节顺序是指占内存多于一个字节类型的数据在内存中的存放顺序,通常有小端、大端两种字节顺序。

    小端字节序指低字节数据存放在内存低地址处,高字节数据存放在内存高地址处;

    大端字节序是高字节数据存放在低地址处,低字节数据存放在高地址处。


    正因为有字节顺序的差别,所以在网络传输的时候定义了所有字节顺序相关的数据都使用big-endian,BSD的代码中定义了四个宏来理:

    ```
    #define ntohs(n) //网络字节顺序到主机字节顺序 n代表net, h代表host, s代表short
    #define htons(n) //主机字节顺序到网络字节顺序 n代表net, h代表host, s代表short
    #define ntohl(n) //网络字节顺序到主机字节顺序 n代表net, h代表host, s代表long
    #define htonl(n) //主机字节顺序到网络字节顺序 n代表net, h代表host, s代表long
    ```

    计算机容量单位的换算关系:

    ```
    1Byte=8bit
    1KB=1024B
    1MB=1024KB
    1GB=1024MB
    1TB=1024GB
    1PB=1024TB
    1EB=1024PB
    1ZB=1024EB
    1YB=1024ZB
    ```

    各种数据类型的取值范围

    ```
    char -128 ~ +127 (1 Byte)
    short -32767 ~ + 32768 (2 Bytes)
    unsigned short 0 ~ 65536 (2 Bytes)
    int -2147483648 ~ +2147483647 (4 Bytes)
    unsigned int 0 ~ 4294967295 (4 Bytes)
    long == int
    long long -9223372036854775808 ~ +9223372036854775807 (8 Bytes)
    double 1.7 * 10^308 (8 Bytes)
    unsigned int 0~4294967295
    long long的最大值9223372036854775807
    long long的最小值-9223372036854775808
    unsigned long long的最大值1844674407370955161
    __int64的最大值9223372036854775807
    __int64的最小值-9223372036854775808
    unsigned __int64的最大值18446744073709551615
    ```
    #### iOS的类型字节大小

    ```
    Base integer types for all target OS's and CPU's
    UInt8 8-bit unsigned integer
    SInt8 8-bit signed integer
    UInt16 16-bit unsigned integer
    SInt16 16-bit signed integer
    UInt32 32-bit unsigned integer
    SInt32 32-bit signed integer
    UInt64 64-bit unsigned integer
    SInt64 64-bit signed integer
    ```

    #### iOS的字节序

    ```
    if (NSHostByteOrder() == NS_LittleEndian) {
    NSLog(@"小端字节序");
    }else if(NSHostByteOrder() == NS_BigEndian){
    NSLog(@"大端字节序");
    }else {
    NSLog(@"未知");
    }
    ```

    通过上述代码打印出来的log,可以知道iOS系统目前采用的是小端序。因此在进行socket网络传输之类的工作时,要记得先把字节序进行转换,然后再传输。iOS自身提供了相应的转换方法,如下:

    ```
    UInt16 byte = 0x1234;
    HTONS(byte);//转换
    NSLog(@"Byte == %x",Byte);//打印出来发现顺序变了
    ```

    上述代码中 HTONS(x) 是对2字节进行转换,为什么是2个字节?从Xcode里点进去你就会发现`typedef unsigned short`,而`unsigned short`是2个字节的,也可以根据上面的类型字节大小转换,`UInt16 ``16bit`,而`1Byte=8bit`,所以是2个字节,如果要对4字节进行转换,就要用 HTONL(x)进行转换了,要对更高字节,比如8字节(64位)进行转换,就要自己写转换的方法了。




    参考文章:

    http://alex1212112.github.io/ios/2014/08/12/ioszhong-de-zi-jie-xu.html
    http://blog.csdn.net/wanwenweifly4/article/details/6627122
    http://blog.csdn.net/will130/article/details/48735769<br>
    http://lib.csdn.net/article/c/26419