I'm trying to create a function that converts uint16_t into uint8_t[2] in C.
The following code has been tested, but even after reading the disassembly, I'm not sure it's portable or safe.
static inline uint8_t* write_u16(uint16_t in, uint8_t out[2], ArchEndian_t endian) {
if (NATIVE_ENDIAN != endian){
in = byte_swap(in);
}
*((uint16_t*)out) = in; //< Is this portable and safe?
return out;
}
How should I think about typecasting in C?
Using a cast for this violates the strict aliasing requirement.
You should instead use
memcpythis way: