I read this code in a library which is used to display a bitmap (.bmp) to an LCD.
I do really hard in understanding what is happening at the following lines, and how it does happen.
Maybe someone can explain this to me.
uint16_t s, w, h;
uint8_t* buffer; // does get malloc'd
s = *((uint16_t*)&buffer[0]);
w = *((uint16_t*)&buffer[18]);
h = *((uint16_t*)&buffer[22]);
I guess it’s not that hard for a real C programmer, but I am still learning, so I thought I just ask 🙂
As far as I understand this, it sticks somehow together two uint8_tvariables to an uint16_t.
Thanks in advance for your help here!
In the code you’ve provided,
buffer(which is an array of bytes) is read, and values are extracted intos,wandh.The
(uint16_t*)&buffer[n]syntax means that you’re extracting the address of the nth byte ofbuffer, and casting it into auint16_t*. The casting tells the compiler to look at this address as if points at auint16_t, i.e. a pair ofuint8_ts.The additional
*in the code dereferences the pointer, i.e. extracts the value from this address. Since the address now points at auint16_t, auint16_tvalue is extracted.As a result:
sgets the value of the firstuint16_t, i.e. bytes 0 and 1.wgets the value of the tenthuint16_t, i.e. bytes 18 and 19.hgets the value of the twelvethuint16_t, i.e. bytes 22 and 23.