Giorgos
Giorgos

Reputation: 36

Convert and Store struct to binary in C++

I want to convert a struct, which consists of various data types (long, char[x], char*), to binary and store it in a variable (I do not know the correct or optimal data type for this).

CONVERSION
For strings: I have converted every character to its ascii code and then converting the ascii code from decimal to binary. For numbers: I have converted the number from decimal to binary.

STORAGE
I stored the output of the above conversions to char[], which consisted of '0' and '1'.

My question is, how to perform a conversion of a struct to binary and in what data type to store it. Ideally, i would like to store it in binary format, in order to perform various actions on it. (the char[] data type I used seems a little wrong, because it is string actually, not binary)

EDIT: I would prefer to avoid using libraries that are not included in standard C++.

Upvotes: 0

Views: 1464

Answers (2)

Alireza_Armn
Alireza_Armn

Reputation: 37

May it would be better to use a vector of bool as your storge, e.g., convert each datatype as you told and then put their output in vector and then retrieve them in the order that they were placed in the container. Although, it's better to use a vector of std::byte.

Upvotes: 0

Paul Evans
Paul Evans

Reputation: 27567

I stored the output of the above conversions to char[], which consisted of '0' and '1'.

Simply store the binary data as bytes instead (eg not ['1','1','1','1','0','1','1','1'] but 0xf7). Store 8 bits per char for as many chars as you have data. If you're using c++17 use std::byte instead of char.

Upvotes: 0

Related Questions