0

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++.

Giorgos
  • 36
  • 1
  • 1
  • 6
  • 4
    Does this answer your question? [Is it possible to serialize and deserialize a class in C++?](https://stackoverflow.com/questions/234724/is-it-possible-to-serialize-and-deserialize-a-class-in-c) – Botje Jan 06 '20 at 12:59
  • You're mixing concepts. A struct _is_ a type (a user-defined type), while a variable _has_ a type. A variable definitely can have a struct type. Also, each character already _has_ a binary value. That's how computers work. – MSalters Jan 06 '20 at 13:34
  • @Botje I would prefer not to use other libraries, but i will give it a try probably, thanks – Giorgos Jan 14 '20 at 17:24
  • @MSalters I know the concepts of structs and variables. My problem is not the type actually. Both structs (that consist of variables) and variables occupy a "place" in memory. So i would like to handle that "place of memory" (their binary values) somehow. – Giorgos Jan 14 '20 at 17:30

2 Answers2

0

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.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
0

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.

Alireza_Armn
  • 37
  • 1
  • 9
  • do you know if i can perform bitwise operations in vectors? – Giorgos Jan 14 '20 at 17:32
  • There is a bunch of solutions and examples for bitwise operations in vectors. take a look in here as an instance: https://stackoverflow.com/questions/4048749/bitwise-operations-on-vectorbool – Alireza_Armn Jan 15 '20 at 07:46