iOS基础之网络字节顺序的转换

时间:2022-12-13 23:21:19

前言

前些阶段在简单的网络开发中碰到了如何将传递过来的字节序列指定位置的几个字节转化成值的问题,这篇文章简单的记录了实现的方法

正文

下面一段代码中,dataBuffer是NSMutableData类型,里面存放了一定长度的字节序列。现从position的索引为9的字节开始,将连续的4个字节内容转换成值(这个值是UInt32 sizeof为4字节)。这时候dataIndex的数字还需要转换一下,使用的是ntohl(),得到的数字就是所需要的值了

    UInt32 dataIndex;
    [self.dataBuffer getBytes:&dataIndex range:NSMakeRange(9, sizeof(dataIndex))];
    dataIndex = ntohl(dataIndex);

⚠️important note:ntohl是将网络传递过来的字节序列中的4个字节的内容转换成数值,而thons是将 网络传递过来的字节序列中的2个字节的内容转成数值

那么如何将UInt32的值存放到指定的4个字节序列中呢?如下代码通过位运算来实现

    UInt32 blockIndex = (UInt32)self.fileReader.blockIndex;
    blockIndexArray[0] = (blockIndex >> 24) & 0xff;
    blockIndexArray[1] = (blockIndex >> 16) & 0xff;
    blockIndexArray[2] = (blockIndex >> 8) & 0xff;
    blockIndexArray[3] = blockIndex & 0xff;

要对更高字节,比如8字节(64位)进行转换,就要自己写转换的方法了。下面是4字节转换(可直接用ntohl),8字节或更多同理

- (UInt32)endianTransferFor32Bit:(UInt32)origin { return ((origin >> 24) & 0xff) | ((origin >> 8) & 0xff00) | ((origin << 8) & 0xff0000) | ((origin << 24) & 0xff000000); }

参考资料

ios 网络字节顺序的转换HTOS