Some parts of this C code don't make sense to me

Hi, given this code:

uint16_t dest_pid; uint8_t *p; pf->dest_pid = p[0] + (p[1] << 8) //(p[1] << 8) equals 0 right? 

This code is part of the embedded operating system driver. Some ideas, what could be the idea behind this statement? Or maybe I'm missing something?

+6
source share
2 answers

First: dest_pid after pf is part of the structure, and I think this is another variable, and then uint16_t dest_pid;

Second: p is a pointer to uint8_t , when you execute (p[1] << 8) , you change what is inside the pointer to 8, for example, if p[1] = 0xE5 after switching it will be 0xE500 . Remember that you put your result in dest_pid , which is a 2 byte variable.

The translation of the last line is likely to take the least significant byte (less significant) pid and add it to the highest byte (shifted by 8) pid and placing it in pf->dest_pid , you might think why it did not send 2 bytes from the beginning, and the reason for this may be that it receives it from the bus, which sends only bytes per unit of time (cycle).

+4
source

I assume your p makes sense to initialize (point to some valid location).

Then at p[0] + (p[1] << 8) p[1] will implicitly advance to unsigned before performing the left shift << 8 , so the code makes sense (for example, on 32-bit processors such as ARM) . Unofficially, it makes a 16-bit number whose lower 8 bits are from p[0] and above 8 bits from p[1]

In the general case, the implicit rule is that in C arithmetic operations are at least on int (and never on smaller pieces of data such as short or uint8_t or char ). But the details are more complex (and have evolved a bit from C89 to C99 and C11).

+8
source

All Articles