繁体   English   中英

分解一个32位整数,并使用后半部分16位形成一个整数

[英]break a 32bit integer, and use the second half 16bit to form an int

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

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

        //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荷兰国际集团在原地,而你需要的高字节偏移, OR与低字节吧:

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

但是,这在可读性方面不是最佳的:如果您以32位整数开头,并且需要切掉高16位,则可以简单地移位16位,并使用0xFFFF掩码-即,您切割的方式相同取出第三个字节,但带有16位掩码。

您不需要逐字节执行此操作。 尝试这个:

   //CID is a 32bit integer, in nslog it shows as 68913219 - its different for every user
    uint16_t value = (CID>>16)&0xffff;

您也可以使用NSData。

如果您有这个整数:

int i = 1;

您可以使用 :

NSData *data = [NSData dataWithBytes: &i length: sizeof(i)];

然后,要获得第二个16位,请执行以下操作:

int16_t recover; [data getBytes: &recover range: NSMakeRange(2, 2)]

然后,您在“恢复”上有16位。

也许这种方式并不像位操作那样高效,但是更清楚。

:d

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM