468,309 Members | 1,140 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,309 developers. It's quick & easy.

Write short to file in binary format

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
2 3959
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
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.

Similar topics

6 posts views Thread by Betty Hickman | last post: by
3 posts views Thread by garyatusa | last post: by
4 posts views Thread by Thomi Aurel RUAG A | last post: by
6 posts views Thread by aagarwal8 | last post: by
1 post views Thread by =?Utf-8?B?U3RldmVU?= | last post: by
1 post views Thread by xiao | last post: by
6 posts views Thread by A.Rocha | last post: by
4 posts views Thread by Keith G Hicks | last post: by
reply views Thread by NPC403 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.