views:

111

answers:

4
int x = 5;
cout<<(char)x;

the code above outputs an int x in raw binary, but only 1 byte. what I need it to do is output the x as 4-bytes in binary, because in my code, x can be anywhere between 0 and 2^32-1, since

cout<<(int)x;

doesn't do the trick, how would I do it?

+2  A: 

You can use the std::ostream::write() member function:

std::cout.write(reinterpret_cast<const char*>(&x), sizeof x);

Note that you would usually want to do this with a stream that has been opened in binary mode.

James McNellis
ok, I'll keep that in mind, thanks!
+1  A: 

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;
Martin York
A: 

A couple of hints.

First, to be between 0 and 2^32 - 1 you'll need an unsigned four-byte int.

Second, the four bytes starting at the address of x (&x) already have the bytes you want.

Does that help?

John at CashCommons
A: 

and what about this?

int x = 5;
cout<<(char) ((0xff000000 & x) >> 24);
cout<<(char) ((0x00ff0000 & x) >> 16);
cout<<(char) ((0x0000ff00 & x) >> 8);
cout<<(char) (0x000000ff & x);

KikoV
Very possibly this is more on the right track than the other answers -- the original question doesn't specify "write in binary" *how*. If it's "however it happens to be in memory", that's one thing, but if you're trying to be compatible with anything else, then you might want to (for instance) always write a 32-bit long in network byte order, as this answer does (modulo some compatibility issues)
hobbs