Encoding, decoding an integer to a char array

后端 未结 10 2261
借酒劲吻你
借酒劲吻你 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:19

    You're storing as ASCII, where you should be storing the bytes themselves.

    The encoding should be something like:

    uint32_t a = 0xff00ffaa;
    unsigned char byte_array[1024];
    

    Notice how I made your target array unsigned, to indicate that it's "raw bytes", and not actually characters.

    byte_array[0] = a >> 24;
    byte_array[1] = a >> 16;
    byte_array[2] = a >> 8;
    byte_array[3] = a >> 0;
    

    This serializes the variable a into the four first bytes of byte_array using big-endian byte ordering, which is sort of the default for many network protocols.

    You may also want to see my answer here: question 1577161.

提交回复
热议问题