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
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;
A bit late, but, as Katy shows in her blog, this might be an elegant solution:
#include <bitset>
#include <iostream>
int main(){
int x=5;
std::cout<<std::bitset<32>(x)<<std::endl;
}
taken from: https://katyscode.wordpress.com/2012/05/12/printing-numbers-in-binary-format-in-c/
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);
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.
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?