Bytes operation

Hi anyone can explain to me why need to shift the byte? as those 3 bytes are specified in data sheet which will contained the return value from slave.

  *adc_object = ((uint32_t)buffer[1] << 16) | ((uint32_t)buffer[2] << 8) |
                (uint32_t)buffer[3];
  *adc_ambient = ((uint32_t)buffer[4] << 16) | ((uint32_t)buffer[5] << 8) |
                 (uint32_t)buffer[6];

buffer[0] contained status information from slave which I can understand.It just I cannot understand and visualized why bytes shifting needed in this case for buffer[1]–>[5]

Thanks in advance

It looks like three 8-bit values are being merged together into a single 32-bit value. There are other ways to do it but that almost always shifting the bytes so they land in the right place in the 32-bit value.

Note that the bytes have to be ‘cast’ as larger types BEFORE they are shifted. If you shift a byte left by 8 or more bits, the bits all fall off the end of the byte and the result is zero.

A way to do it without explicit casting:

  uint32_t result = buffer[1] ;
  result = (result << 8) | buffer[2];
  result = (resuot << 8) | bufer[3];

johnwasser:
It looks like three 8-bit values are being merged together into a single 32-bit value. There are other ways to do it but that almost always shifting the bytes so they land in the right place in the 32-bit value.

Note that the bytes have to be ‘cast’ as larger types BEFORE they are shifted. If you shift a byte left by 8 or more bits, the bits all fall off the end of the byte and the result is zero.

A way to do it without explicit casting:

  uint32_t result = buffer[1] ;

result = (result << 8) | buffer[2];
  result = (resuot << 8) | bufer[3];

To match the OP

  uint32_t result = buffer[3] ;
  result = (result << 8) | buffer[2];
  result = (resuot << 16) | bufer[1];

blh64:
To match the OP

  uint32_t result = buffer[3] ;

result = (result << 8) | buffer[2];
 result = (result << 16) | buffer[1];

Are you SURE? If we assume the three buffer positions contain 0xB1, 0xB2, and 0xB3 it looks like yours would produce:

0xB3B200B1

The OP’s code produces:

0x00B1B2B3

(same as mine)[/code]

The OP's code shifts byte1 by 16 bits, byte 2 by 8 bits and byte3 by 0 bits.

Your code doesn't do either, since you shift two of the bytes by 8 bits (one should be 16)

blh64:
The OP's code shifts byte1 by 16 bits, byte 2 by 8 bits and byte3 by 0 bits.

Your code doesn't do either, since you shift two of the bytes by 8 bits (one should be 16)

Note that byte1 is put in result and then result is shifted left by 8 bits, TWICE. As a result, byte1 is shifted left 16 bits.

You are correct. I was missing the fact that result is being shifted :slight_smile: