What’s the best/recommended way to copy data between a byte array and an integer in C? Currently I’m using memcpy, which doesn’t feel right to me. A sample of the sort of thing I’m doing is below.
struct alpha {
unsigned char byte_array[20];
}
void function(struct alpha *st) {
unsigned long num;
/* Do some stuff */
memcpy(st->byte_array, &num, sizeof(unsigned long));
/* Do more stuff */
memcpy(&num, st->byte_array, sizeof(unsigned long));
}
I assume I want to use casts somehow, but I’m not confident of how casting and pointer (de)referencing interacts, particularly when arrays get involved.
memcpyis the standard and portable tool for that effect. Modern optimized compilers will inline this call to something well adapted to your situation, e.g data types, allignement, size (if known at compile time), processor… So I think you should definitively stick to that and not mess around with some handmade optimizations.