user489041
user489041

Reputation: 28312

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

Upvotes: -1

Views: 853

Answers (4)

paxdiablo
paxdiablo

Reputation: 882646

That's a very long-winded way of just converting four 8-bit bytes into a 32-bit long.

The anding with 0xff is just ensuring that only the lower 8 bits of each value are used (0xff == binary 11111111).

The bit-shifting (in multiples of 8) is just to get each character into the right position.

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().

Upvotes: 3

phoxis
phoxis

Reputation: 61990

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

Upvotes: 0

alvin
alvin

Reputation: 1196

looks like it is going for an endian independent conversion.

Upvotes: 1

Graham Borland
Graham Borland

Reputation: 60721

It looks like it's building an integer from an array of 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. The masking is to prevent the sign bit from flooding the destination variable.

Upvotes: 1

Related Questions