By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,214 Members | 1,195 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,214 IT Pros & Developers. It's quick & easy.

Write short to file in binary format

P: n/a
I have the following:

short x = 3;
...
std:ofstream file(outfile.txt, std::ios::out|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

Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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::out|std::ios::trunc);
file << aByte << endl;
return 0;
}

Good Luck,
Kyle

"randy1200" <ra*******@yahoo.com> wrote in message
news:9b******************************@localhost.ta lkaboutprogramming.com...
I have the following:

short x = 3;
..
std:ofstream file(outfile.txt, std::ios::out|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

Jul 23 '05 #2

P: n/a
That's exactly what I needed. Many thanks...

Randy

Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.