0

I am trying to understand this bit of code.

uint8_t input[4];//Just the relevant bits of code here
unsigned int s = (input[0] << 24) | (input[1] << 16) | (input[2] << 8) | input[3];

So I guess my main question is, is it relevant to keep the first two bit shifts? I really don't know exactly what is going on here. As far as I knowt the first shift is a 24 bit right shift on the first element of the input array which is then OR'd with the next element. But won't this always just be zero since the element is only 8 bits in length? Or am I missing something.

Fred
  • 1,486
  • 1
  • 9
  • 6
  • 4
    [Implicit type promotion rules](https://stackoverflow.com/q/46073295/364696) mean you never actually do math with sizes smaller than `int`. – ShadowRanger Dec 14 '20 at 02:32
  • 1
    This looks like it's reversing the [endian order](https://en.wikipedia.org/wiki/Endianness) of a 32-bit int. – tadman Dec 14 '20 at 02:33
  • @ShadowRanger so does that mean the uint8_t input[4] is stored in an int behind the scenes? – Fred Dec 14 '20 at 02:36
  • 2
    @Fred: No. You can *store* smaller values. But when you *use* them, the math is done with (at least) `int`, and possibly narrowed when it's done (if you store to something smaller than `int`; you don't in this case). – ShadowRanger Dec 14 '20 at 02:37
  • Gotcha, now I understand how it's working thanks a lot. – Fred Dec 14 '20 at 02:39
  • So I guess it would be better to write `((uint32_t)input[0] << 24) | ((uint32_t)input[1] << 16) | ((uint32_t)input[2] << 8) | (uint32_t)input[3];` – Fred Dec 14 '20 at 02:51

0 Answers0