cstm32i2cmcu

Copy larger size variable unit16 to equivalent smaller array size unint8 by casting in c


I have variable uint16_t value, I want to copy it to uint8_t buffer[3]. Is it possible to do (Little endian):

*buffer=*(uint8_t *)&value;

Instead of:

buffer[0] = highByte(value);
buffer[1] = lowByte(value);

Since this replacement cause stm32f7 I2C to not working correctly. Is there any correct casting?


Solution

  • Assuming to resolve the problem related to high side and low side as mentioned by @Lundin, and The fact that dereferencing uint8_t grant access to only it's first array element, I reached this solution by only a single cast:

    *(uint16_t*) buffer=value;
    

    Which is reduced version of:

    uint16_t* p;
    p= buffer;
    *p=value;