declaration of binary variables

Jun 7, 2010 at 11:31am
hi, sorry for posting this here since this might be a beginner's question:

I need do declare variables with the attribute "binary" - a friend told me i could use this for my problem which is as follows:
I need to create a binary file (which is no problem) and then save variables to that file so that e.g. a double var reserves 4 bytes in that file and fills them with the binary equivalent of its value.

How do i declare variables so that they appear as binary digits when i send them ofstream?

Many thanks

Alex
Jun 7, 2010 at 11:54am
You don't have to declare your variables in a different way. You only have to open the file in binary mode and use the write/read methods instead of the <</>> operators. Take a look here:

http://cplusplus.com/doc/tutorial/files/ (the binary files section is near the bottom of the page)

EDIT: I just noticed that the tutorial only has examples for char arrays...

To output doubles, after you've opened the file for output in binary mode...

ofstream fout("data.dat",ios::binary);

save your doubles to the file like this:

1
2
3
double my_var;
//... enter some value for my_var
fout.write((char*)&my_var,sizeof(my_var));

Later you can read them back like this:

Open the file for input in binary mode...

ifstream fin("data.dat",ios::binary);

and get the value like this:

1
2
double my_var;
fin.read((char*)&my_var,sizeof(my_var));

That's pretty much all of it.
Last edited on Jun 7, 2010 at 12:13pm
Jun 7, 2010 at 12:14pm
many thanks i will try it out in a moment!
Jun 8, 2010 at 10:23am
hi, that really helped me.
still i have got a problem:
what do i do to send only the values into the binary file?
e.g. when i write a double with value "4" because I want to get (to see in the hex viewer)
00 00 00 00 00 00 00 04
i get instead
00 00 00 00 00 00 10 04

probably because of the variable's format?

thank you for any help
alex
Jun 9, 2010 at 12:26pm
If you want that, you have to store it as an int, not as a double. A double's binary representation may not be exactly what you think. That's why hex editors and cheat engines need you to specify the type (int, double, byte etc...) of the value you want them to search when searching for a specific value.

You may also wanna take a look at this:
http://en.wikipedia.org/wiki/Double_precision_floating-point_format
Topic archived. No new replies allowed.