1

I'm writing a networking application using sockets in c++ so lets jump straight to the problem : i'm storing my data as an array of int16_ts (the choice of int16_t being for consistency accross different platforms) , as we know each of these int16_ts would be two consecutive bytes in memory. i want to store each of those bytes in a char so that each int16 would be translated to exactly two bytes and eventually send the entire char* over the socket

please notice that i'm not looking for something such as std::to_string cause i want each int16_t to occupy exactly two bytes.

any help is appreciated !

Paghillect
  • 822
  • 1
  • 11
  • 30

2 Answers2

0

You would need to copy each int16_t one at a time to the char * buffer, calling htons() on each one to translate the bytes into network byte order. Then on the receiving side, you would call ntohs() to convert back.

int send_array(int16_t *myarray, int len, int socket) {
    char buf[1000];
    int16_t *p;
    int i;

    p = (int16_t *)buf;
    for (i=0;i<len;i++) {
        p[i] = htons(myarray[i]);
    }
    return send(socket,buf,len*sizeof(int16_t),0);
}
dbush
  • 205,898
  • 23
  • 218
  • 273
  • Thanks ! thats what i was looking for. i didn't think of writing directly to the char* using an int pointer . – Paghillect Oct 11 '15 at 20:47
  • 1
    @dbush @Parsoa `p = (int16_t *)buf` violates strict aliasing rule, so it is undefined behavior. You should do the opposite: treat `int16_t*` as `char*`. Read http://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule – Stas Oct 11 '15 at 21:44
0

C++ has a new type, char16_t, that's designed to hold UTF-16 characters. If you mean you want to send the 16-bit hints over the wire one byte at a time, convert each one to network byte order with htons(), store them in a new array of uint16_t, then send that array over the socket. If you want to address the array of shorts as an array of bytes, you can do that either through a union, with a pointer cast, or with a reference to an array. Example: char* const p=reinterpret_cast<char*>(&shorts[0]);.

Davislor
  • 14,674
  • 2
  • 34
  • 49