Encoding, decoding an integer to a char array

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

    The use of atoi function is only justified when the string that you are expecting to decode was build by your own code and no further than a couple of lines above. I.e it is only usable in sketch-like code.

    Otherwise, especially in your case, when the data arrives from the network, atoi function cannot be meaningfully used to perform decoding, since it provides no usable error handling mechanism and absolutely no protection from overflow (undefined behavior on overflow). The only function that can be meanigfully used for string-to-integer conversion is a function from the strto... group, strtol in your case.

    0 讨论(0)
  • 2021-02-06 20:29

    Use XDR (RFC 4506).

    0 讨论(0)
  • 2021-02-06 20:30

    At least to be portable you should think about possible different byte order on encoding.

    Do you really need to implement new networking messaging protocol? Don't NASA IPC or Sun RPC suit you? They both are stable enough, NASA is simpler to startup, RPC seems available more widely (yes, it is ready to use and library is available for most popular systems).

    • For RPC try 'man rpc'
    • For NASA IPC look here
    0 讨论(0)
  • 2021-02-06 20:30

    I've looked at this page a million times, and I really appreciate all the other answers for helping me out. Here is the stub I am using, which is unique from other answers because it can be used in a for loop:

    void encode_int_as_char(int num, char *buf, int length){
        int i;
        for (i = 0; i < length; i++){
            buf[i] = (char)(num >> ((8 * (length - i - 1)) & 0xFF));
        }
    }
    
    int decode_int_from_char(char *enc, int length){
        int i, num, cur;
    
        num = 0;
        for (i = 0; i < length; i++){
            cur = (unsigned char) enc[i] << (8 * (length - i - 1));
            num += (int) cur;
        }
    
        return num;
    }
    
    0 讨论(0)
提交回复
热议问题