Try:
int x = 5;
std::cout.write(reinterpret_cast<const char*>(&x),sizeof(x));
Note: That writting data in binary format is non portable.
If you want to read it on an alternative machine you need to either have exactly the same architecture or you need to standardise the format and make sure all machines use the standard format.
If you want to write binary the easiest way to standardise the format is to convert data to network format (there is a set of functions for that htonl() <--> ntohl() etc)
int x = 5;
u_long transport = htonl(x);
std::cout.write(reinterpret_cast<const char*>(&transport), sizeof(u_long));
But the most transportable format is to just convert to text.
std::cout << x;
cout
, because you don't have control over how it's opened. If you want to do binary output, open your own stream and include theios_base::binary
flag in youropenmmode
argument. – Chivalric