Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array?
I was looking for an answer but didn\'t get a
It's probably best to use some existing tool. If you can't - do you care about endianness (i.e. is this a cross platform protocol?)
Otherwise, you can simply do something like...
unsigned char msg[1024];
int writeIndex = 0;
[...]
int mynum = 12345;
memcpy(msg + writeIndex , &mynum, sizeof mynum);
writeIndex += sizeof mynum;
and to decode
//[...] also declare readIndex;
memcopy(&mynum, msg + readIndex, sizeof mynum);
readIndex += sizeof mynum;
(you could replace the notion of msg + index
with an unsigned char pointer, though this is unlikely to matter).
Using memcpy like this is liable to be slower, but also more readable. If necessary, you could implement a memcopy clone in a #define or inline function - it's just a short loop of assignments, after all.