Hi. I know that Cortex M0 memory transfers must be aligned.
Knowing that, I'm still not sure if the code below is safe? It compiles and it works, but I'm not sure if I'm just lucky?
unsigned int MCUSerialNumber; unsigned char data[8] = {0}; *((unsigned int *)&data[0]) = MCUSerialNumber;
Is the code above identical in every way to this one?
data[0] = MCUSerialNumber & 0xFF; data[1] = (MCUSerialNumber >> 8) & 0xFF; data[2] = (MCUSerialNumber >> 16) & 0xFF; data[3] = (MCUSerialNumber >> 24) & 0xFF;
It is safe because 'data' is aligned. Why introduce a doubt when your other version works without any doubt, as would:
memcpy(data, &MCUSerialNumber, sizeof MCUSerialNumber);
It is safe because 'data' is aligned.
Can you please explain why is "data" aligned? In my case "data" is of char type and can be at any address?
Thanks.
I retract my "is aligned" statement. Unless the two objects are in a structure, there is no guarantee that 'MCUSerialNumber' and 'data' are in contiguous memory locations for 'data' to be aligned as a result of it following an aligned object.
So to conclude, the short version of my code is not safe?
The M0, like the ARM7/9, can be intolerant of reads/writes of 32-bit words to unaligned addresses, as are a number of MIPS implementations. The use of memcpy() is the portable way to do this. The endian-ness of the core will also impact byte order.