简体   繁体   English

C按位运算问题

[英]C Bitwise Operation Question

Can someone help me understand whats going on with this code. 有人可以帮助我了解这段代码的情况。 It looks like it is making an integer from an array of bits. 看起来它是从一个位数组中得出一个整数。 Im not sure how its doing that. 我不确定它是如何做到的。 Why is there a bitwise & operation on OxFF? 为什么在OxFF上进行按位与运算? Inst this just going to produce the same result? 这样做会产生相同的结果吗?

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

That's a very long-winded way of just converting four 8-bit bytes into a 32-bit long. 这只是将4个8位字节到一个32位长的啰嗦的方式。

The and ing with 0xff is just ensuring that only the lower 8 bits of each value are used ( 0xff == binary 11111111 ). 0xffand只是确保仅使用每个值的低8位( 0xff == binary 11111111 )。

The bit-shifting (in multiples of 8) is just to get each character into the right position. 移位(8的倍数)只是为了使每个字符都位于正确的位置。

The whole thing could be replaced with something like: 整个事情可以替换为:

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);

Or, alternatively (and assuming they're available), use the correct tools for the job, specifically htonl() and ntohl() . 或者,替代地(并假设它们可用),使用正确的工具进行工作,特别是htonl()ntohl()

It looks like it's building an integer from an array of bytes . 看起来它是从bytes数组构建一个整数。 It may be that analog_val_ptr[] is an array of int or short values, and this code is designed to treat each entry as a byte. 可能analog_val_ptr[]是一个intshort值的数组,并且此代码旨在将每个条目视为一个字节。 The masking is to prevent the sign bit from flooding the destination variable. 屏蔽是为了防止符号位泛滥目标变量。

看起来要进行字节序独立转换。

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

After the AND operation the lower 8 bits will be found with var & 0xff . 在AND操作之后,将通过var & 0xff找到低8位。 Its a way to only cut out the needed portion, masking. 它是一种仅切出所需部分的方法,即遮罩。

The code above simply pastes the lower bytes of 4 array elements into the variable ltemp as a long int. 上面的代码只是将4个数组元素的低字节ltemp为long int变量ltemp

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

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