Serialize Strings, ints and floats to character arrays for networking WITHOUT LIBRARIES

后端 未结 4 816
我寻月下人不归
我寻月下人不归 2020-12-29 11:48

I want to transmit data over the network, but I don\'t want to use any foreign libraries (Standard C/C++ is ok).

for example:

unsigned int x = 123;
c         


        
4条回答
  •  灰色年华
    2020-12-29 12:23

    Something like the code below would do it. Watch out for problems where sizeof(unsigned int) is different on different systems, those will get you. For things like this you're better off using types with well-defined sizes, like int32_t. Anyway...

    unsigned int x = 123;
    char y[3] = {'h', 'i', '\0'};
    float z = 1.23f;
    
    // The buffer we will be writing bytes into
    unsigned char outBuf[sizeof(x)+sizeof(y)+sizeof(z)];
    
    // A pointer we will advance whenever we write data
    unsigned char * p = outBuf;
    
    // Serialize "x" into outBuf
    unsigned int32_t neX = htonl(x);
    memcpy(p, &neX, sizeof(neX));
    p += sizeof(neX);
    
    // Serialize "y" into outBuf
    memcpy(p, y, sizeof(y));
    p += sizeof(y);
    
    // Serialize "z" into outBuf
    int32_t neZ = htonl(*(reinterpret_cast(&z)));
    memcpy(p, &neZ, sizeof(neZ));
    p += sizeof(neZ);
    
    int resultCode = send(mySocket, outBuf, p-outBuf, 0);
    [...]
    

    ... and of course the receiving code would do something similar, except in reverse.

提交回复
热议问题