Write short to file in binary format

R

randy1200

I have the following:

short x = 3;
...
std:eek:fstream file(outfile.txt, std::ios::eek:ut|std::ios::trunc);
...
file << x << endl;

Of course, "3" shows up in the file. What I'd really like to see is
"00000011". I'd be very surprised to see that C++ doesn't already have an
operator to do this for me.

Thanks,
Randy
 
K

Kyle Kolander

This will do what you want... there may be a better solution.
You can use the standard library bitset template class.
The templated value is the number of bits ( 8 * sizeof(short) ) will usually
be 16.

#include <fstream>
#include <bitset>
using namespace std;

int main(int argc, char* argv[])
{
short x = 3;
bitset<(8 * sizeof(short))> aByte(x);
ofstream file("outfile.txt", std::ios::eek:ut|std::ios::trunc);
file << aByte << endl;
return 0;
}

Good Luck,
Kyle
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,169
Latest member
ArturoOlne
Top