Thread: Not atoi, not sprintf, but "int coded into char*"

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    28

    Not atoi, not sprintf, but "int coded into char*"

    (this is to be solved in ANSI C, not really ANSI required but it'd be great not to get warnings with -Wall)

    This program packs, sends and recieves Descriptors according to the Gnutella Protocol Specification...not really relevant, just read this struct for example:


    Code:
    struct tpong
    {
    struct theader header;
    char port[2];
    char ip[4];
    char nfiles[4];
    char nkbytes[4];
    };
    I also calculate things like nfiles and nkbytes, and get port and ip as parameters. BUT some of these data I recieve or gather come as numeric data type (int...). So I haven't been able to pack the number into the string, and get it back as well. Moreover, as you see char* size is not necessarily 4 bytes (as int).

    HELP!! Thx in advance!

    Mariano Lopez-Gappa (20) from Argentina


    EDIT: just a tiny comment: char vector lengths are not wrong since G.P.S. says not to save space for NULL terminators (so strlen, strcat, strcpy, strcmp is NO GOOD )

  2. #2
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    I don't know what your question is, but could it be that the arrays in that struct contain the binary representation of int instead of string? For example
    Code:
    long n = 123;
    struct tpong t;
    memcpy(t.ip, &n, sizeof(long));
    The above will work as long as sizeof(long) does not exceed 4.

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    28
    yaya, THAT'S IT, so its memcpy, thx Ancient Dragon. But there's still an issue. What if I got an int being the port number, which is to be stored in a char[2]?

    A 4-byte-int won't fit on a char[2]...should I memcpy only the first 2 bytes? I've read that this may work only if int's are saved in little endian format, cause the 2 less significant bytes would be first....no clue though...

    Thanks in advance once again.

    Mariano Lopez-Gappa

  4. #4
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    You can declare it as short, which is normally (but maybe not always) 2 bytes in 32-bit compilers.
    Code:
    short p;
    memcpy(&p, t.port,sizeof(short));
    
    // or just a simple assignment
    int port = *(short *)t.port;
    Last edited by Ancient Dragon; 11-25-2005 at 06:38 PM.

  5. #5
    Registered User
    Join Date
    Nov 2005
    Posts
    28
    ok thx a lot ill be doing that. THX !

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Perhaps you need to look up what endian means - particularly big endian and little endian.

    Then learn about htons() and it's related functions.

Popular pages Recent additions subscribe to a feed