OGeek|极客世界-中国程序员成长平台

标题: ios - 打破一个 32bit 整数,并使用后半部分 16bit 形成一个 int [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 07:26
标题: ios - 打破一个 32bit 整数,并使用后半部分 16bit 形成一个 int

我正在制作一个从服务器下载 32 位整数的应用,并将第一个 16 位和第二个 16 位用于不同目的...

我负责第二个16bit,应该用来形成一个int,我知道我应该使用按位运算来做到这一点,但无法实现,下面是我正在使用的代码,请给我更多信息.

        //CID is a 32bit integer, in nslog it shows as 68913219 - its different for every user
        Byte lowByte = (CID>>16)&0xFF; //the 3rd byte
        Byte highByte = (CID>>24)&0xFF; //the 4th byte
        uint16_t value = lowByte & highByte; //combine, but the result is 0.



Best Answer-推荐答案


uint16_t value = lowByte & highByte; //combine, but the result is 0.

这不是您将两个字节组合成一个 uint16_t 的方式:您是在对它们进行 AND 操作,而您需要移动高字节,并且 OR 它与低字节:

uint16_t value = lowByte | (((uint16_t)highByte) << 8);

然而,这在可读性方面不是最理想的:如果你从一个 32 位整数开始,并且你需要去掉高 16 位,你可以简单地移位 16,并用 0xFFFF - 即与剪切第三个字节的方式相同,但使用 16 位掩码。

关于ios - 打破一个 32bit 整数,并使用后半部分 16bit 形成一个 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22853583/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4