Encoding, decoding an integer to a char array

后端 未结 10 2263
借酒劲吻你
借酒劲吻你 2021-02-06 19:44

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

10条回答
  •  迷失自我
    2021-02-06 20:18

    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.

提交回复
热议问题