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

后端 未结 4 809
我寻月下人不归
我寻月下人不归 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:15

    Ah, you want to serialize primitive data types! In principle, there are two approaches: The first one is, that you just grab the internal, in-memory binary representation of the data you want to serialize, reinterpret it as a character, and use that as you representation:

    So if you have a:

    double d;

    you take the address of that, reinterpret that pointer as a pointer to character, and then use these characters:

    double *pd=&d;
    char *pc = reinterpret_cast(pd); 
    for(size_t i=0; i

    This works with all primitive data types. The main problem here is, that the binray representation is implementation dependent (mainly CPU dependent). (And you will run into subtle bugs when you try doing this with IEEE NANs...).

    All in all, this approach is not portable at all, as you have no control at all over the representation of your data.

    The second approach is, to use a higher-level representation, that you yourself have under control. If performance is not an issue, you could use std::strstream and the >> and << operators to stream primitive C type variables into std::strings. This is slow but easy to read and debug, and very portable on top of it.

提交回复
热议问题