2011-08-25 82 views
0

有人可以帮助我理解此代码正在发生什么。它看起来像是从一个数组中创建一个整数。我不知道它是如何做到这一点。为什么在OxFF上有一个按位操作&? Inst这会产生相同的结果?C位操作问题

//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 
+0

analog_val_ptr的类型是什么?它看起来像程序员试图通过使用'&0xFF'并转换为'unsigned char'来加倍确定。我想它们都可以自己做。 – john

+0

它的一个字节,数据从套接字进入 – user489041

回答

3

这只是将4个8位字节到一个32位长非常啰嗦的方式。

and0xff只是确保只使用每个值的低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()

整个事情可能喜欢的东西来代替。

+0

'&0xff'并转换为'unsigned char'完全是多余的。一个或另一个应该被删除,可能是演员。 –

+0

作为一个风格问题,结果可能是一个'unsigned long',只是为了明确结果。 –

+0

@Kerrek,好点,修改来修复。 – paxdiablo

1

它看起来像从字节的数组构建整数。这可能是analog_val_ptr[]是一个intshort值的数组,此代码旨在将每个条目视为一个字节。屏蔽是为了防止符号位溢出目标变量。

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

AND操作的低8位之后将与var & 0xff被发现。它的一种方法是只剪掉所需的部分,掩盖。

上面的代码只是将4个数组元素的低位字节作为long int粘贴到变量ltemp中。

+0

'&'是AND,而不是XOR – Hasturkun

+0

我已经疯了。对不起,纠正.. – phoxis

1

看起来像是要进行endian独立转换。