Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Copy large size variable to smaller array size by casting in c

I have variable uint16 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

STM32 is little endian so you get the lowest significant byte first:

uint8_t* ptr = (uint8_t*)&value;
uint8_t low  = ptr[0];
uint8_t high = ptr[1];

Doing casts and de-referencing like this is fine for character types only. The above code is assuming that uint8_t is a character type, which is very likely the case (on gcc and other mainstream compilers).

For more info see What is CPU endianness?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading