Write in Binary format in a binary file

Hello,

I begin by give my code :
#include <ostream>
#include <istream>
#include <fstream>

namespace std
{
extern istream cin;
extern ostream cout;
// this is explained below
static ios_base::Init __foo; // not its real name
}
using namespace std;
main()
{
ofstream f ("toto.xyz", ios::out | ios::binary);
int x[2] = {1,1};
int i;
if(!f.is_open())
cout << "Impossible d'ouvrir le fichier en écriture !\n";
else
{
for (i = 0; i < 2; i++)
f.write ((char *)&x[i], sizeof(int));
}
cout << "bonjour !!";
f.close();
return 0;
}


The result is a file whith binary value
00000001 00000001


I want to write directly in binary. I want that the file will have for value
00000011


Thank you for reponses and sorry for my english (I am french).
You can use bitshifting to do that:
1
2
3
int x[2] = {1,1};
int v=x[0]<<1 | x[1];
f.write (reinterpret_cast<const char*>(&v),sizeof(v));


By the way,
1
2
3
4
5
6
7
namespace std
{
extern istream cin;
extern ostream cout;
// this is explained below
static ios_base::Init __foo; // not its real name
}

is unnecessary. Instead, include <iostream> (instead of <ostream> and <istream>).

The definition of main is also incorrect. It needs to be int main().
namespace std
{
extern istream cin;
extern ostream cout;
// this is explained below
static ios_base::Init __foo; // not its real name
}
Don't do that. Include <iostream>.

11b is just 3.
1
2
char a=3;
file.write(&a,1);


We can probably give better advice if you tell use what you want to do in more detail.
Thank you for reponses. I am not a C++ beginner but I was not practiced for a quiet long time.

For your solution, Athar, what should I change for that give me 00000111 ?

I want simply write directly in binary in a file.

Thank you for reponses.
Three bits:
1
2
3
int x[3] = {1,1,1};
int v=x[0]<<2 | x[1]<<1 | x[2];
f.write (reinterpret_cast<const char*>(&v),sizeof(v));


Just look up the bitshift operators (<< and >>) and the other bit-wise operators |, & and ~ (or, and, not) to understand what they do.

There is no bit stream class in C++. You can easily create your own, though.
Last edited on
Thank you very much !
I will study the bitshifting.
Bye Bye
Topic archived. No new replies allowed.