C位运算题

C Bitwise Operation Question

本文关键字:运算      更新时间:2023-10-16

有人能帮我理解这段代码是怎么回事吗?它看起来像是在从一个位数组中生成一个整数。我不知道它是怎么做到的。为什么会有位元& &;OxFF上的操作?这个会产生相同的结果吗?

//first take the first  4 bytes read out of the socket into an array and
//make them a 32 bit integer
        long ltemp =0;
        long ltemp2 = 0;
        ltemp  = ltemp | (unsigned char)(analog_val_ptr[0] & 0xff);
        ltemp  = ltemp << 24;
        ltemp2 = ltemp2 | (unsigned char)(analog_val_ptr[1] & 0xff);
        ltemp2 = ltemp2 << 16;
        ltemp = ltemp2 | ltemp;
        ltemp2 =0;
        ltemp2 = ltemp2 | (unsigned char)(analog_val_ptr[2] & 0xff);
        ltemp2 = ltemp2 << 8;
        ltemp = ltemp2 | ltemp;
        ltemp  =  ltemp | (unsigned char)(analog_val_ptr[3] & 0xff);
///then convert that integer into a float, passing

这是一个非常冗长的方法,只是将四个8位字节转换成一个32位字节。

使用0xffand只是确保每个值只使用较低的8位(0xff == binary 11111111)。

移位(以8为倍数)只是为了将每个字符移到正确的位置。

整个东西可以替换成这样:

unsigned long ltemp  = (unsigned char)(analog_val_ptr[0] & 0xff);
ltemp = (ltemp << 8) | (unsigned char)(analog_val_ptr[1] & 0xff);
ltemp = (ltemp << 8) | (unsigned char)(analog_val_ptr[2] & 0xff);
ltemp = (ltemp << 8) | (unsigned char)(analog_val_ptr[3] & 0xff);

或者,或者(假设它们可用),为工作使用正确的工具,特别是htonl()ntohl()

看起来像是在从字节数组中生成一个整数analog_val_ptr[]可能是intshort值的数组,这段代码被设计成将每个条目视为一个字节。屏蔽是为了防止符号位溢出目标变量。

看起来是独立于端序的转换

var = 0x ? ? ? ? ? ? ? ?
         & & & & & & & & 
      0x 0 0 0 0 0 0 f f 
      ------------------
         0 0 0 0 0 0 ? ?

在AND操作之后,将在var & 0xff中找到低8位。这是一种只剪掉所需部分的方法,屏蔽。

上面的代码只是将4个数组元素的较低的字节粘贴到变量ltemp中作为长整型。