cstringbyteshorthtonl

2 byte short into 2 byte string in C?


Any way to convert a a 2 byte short (normal short) into just a 2 byte string (char*) after using htons on that short. The thing is that the htons method returns an int (4 bytes), how do I put it into a 2 byte string ???

Note: I need to be able to use ntohs on the result to get the original value.

Thanks in advice :D


Solution

  • Ahm, how do you say htons returns a 4-byte integer, on my linux, htons has the prototype of

    uint16_t htons(uint16_t hostshort);
    

    Thus you can do

    uint16_t value;
    value = htons(hostshort);
    char *bytes = &value;
    // now the first 2 bytes pointed to by "bytes" are the value in network byte order
    

    Which means the return value is just 2 bytes.

    Then I think it is quaranteed after htons that such bit representation on the returned value is such that the first byte of the value (((unsigned char *)value)[0]) is the most significant, and the second the least significant.