There are 2 variables:
uint32_t var32 = 0xAABBCCDD;
uint8_t var8[4] = { 0, 0, 0, 0 };
Which copying way of var32 to var8 would be faster?
for (size_t i = 0; i < sizeof(uint32_t); i++)
var8[i] = (uint8_t)(var32 >> (i * 8));
or
memcpy(var8, &var32, sizeof(uint32_t));
I would appreciate all hints.
Assuming a 32bit architecture, the memcpy comes down to a single mov (or similar) instruction. So it is faster. But it's also wrong. From a C point of view, you're invoking implementation defined behaviour doing that. What could happen in reality is that your bytes are ordered wrongly, depending on whether you are on a big endian or little endian platform. So, just use the bit shifting solution instead of worrying about performance.
The memcpy in C is generally guaranteed in modern compilers to optimise to being the fastest way of copying available. However this does assume that it is properly inlined in your implementation.
I also do not believe this causes strict aliasing violations as the two pointers never alias the same memory.
However the order of which the bytes of the int is copied into which byte of the array is implementation defined. If you wished to ensure this would instead always be in the big endian order you could first run htonl on the int which would make it big endian, then the results of the copy would be well defined. This would also optimise to nothing in the case it wasnt needed, making it always the fastest implementation on any system.
If on the other hand you want little endian byte ordering use the htole32 to ensure the int becomes little endian on any hardware. However beware that htole32 is an extension in BSD, Linux and various other OSes and isnt guaranteed to be available on all implementations (read, non standard).
I think memcpy will faster, because it dose not compute only use move. byte shift have tow step compute.