Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Standard Way To Encode/Decode To/From Binary Object In C++

Tags:

c++

encode

I want to encode/decode some basic type into/from binary.

The test code may looks like this.

 int main()
{
    int iter = 0;
    char* binary = new char[100];

    int32_t version = 1;
    memcpy(binary, &version, sizeof(int32_t));
    iter+=sizeof(int32_t);

    const char* value1 = "myvalue";
    memcpy(binary+iter, value1, strlen(value1));
    iter+=strlen(value1);

    double value2 = 0.1;
    memcpy(binary+iter, &value2, sizeof(double));
#warning TODO - big/small endian - fixed type length

    return 0;
}

But I still need to solve a lot of problems, such as the endian and fixed type length.

So I want to know if there is a standard way to implement this.

Simultaneously, I don't want to use any third-party implementation, such as Boost and so on. Because I need to keep my code simple and Independent.

If there is a function/class like NSCoding in Objc, it will be best. I wonder if there is same thing in C++ standard library.

like image 720
Ringo_D Avatar asked Dec 20 '25 21:12

Ringo_D


1 Answers

No, there are no serialization functions within the standard library. Use a library or implement it by yourself.

Note that raw new and delete is a bad practice in C++.

like image 131
The Techel Avatar answered Dec 22 '25 13:12

The Techel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!