Encoding, decoding an integer to a char array

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

    What you're doing will sort-of work. You're not transferring the bytes of the data - you're transferring the numeric value of the data. As a result a buffer of size 5 is way too small for the data you're sending (0xFF00FFAA has a numeric value of 4278255530 - 10 bytes).

    To transfer the bytes you need to do something like the following (assumes little endian):

    Encode:

    char array[1024]; // outgoing network data
    int next = 0;
    
    array[next++] = value & 0xFF;
    array[next++] = (value >> 8) & 0xFF;
    array[next++] = (value >> 16) & 0xFF;
    array[next++] = (value >> 24) & 0xFF;
    

    These statements strip off the bytes of the value and assign them to successive values in your array.

    Decode:

    char array[1024]; // incoming network data
    int next = 0;
    
    value = 0;
    value |= (int)*((unsigned char*)array)[next++];
    value |= (int)*((unsigned char*)array)[next++] << 8;
    value |= (int)*((unsigned char*)array)[next++] << 16;
    value |= (int)*((unsigned char*)array)[next++] << 24;
    

    These statements pull the bytes out of the array and push them back into the value.

    If you want to try to optimize your network format and not transfer bytes you can eliminate some of the data. But remember that your sender and receiver need to know from each other what to expect - so there needs to be some communication of what the type or length of data elements being passed is.

提交回复
热议问题