我正在制作一个从服务器下载 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.
最佳答案
uint16_t value = lowByte & highByte; //combine, but the result is 0.
这不是将两个字节组合成一个 uint16_t
的方式:您将它们进行AND
就位,同时需要移动高字节,并且或
它与低字节:
uint16_t value = lowByte | (((uint16_t)highByte) << 8);
但是,就可读性而言,这并不是最理想的:如果您从 32 位整数开始,并且需要删除高 16 位,则可以简单地移位 16,并使用 0xFFFF 进行掩码
- 即与剪切第三个字节相同的方式,但使用 16 位掩码。
关于ios - 分解一个32位整数,并用后半部分16位组成一个int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22853583/