Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

trouble with bit streams

Status
Not open for further replies.

dendog

Programmer
Jun 28, 2001
53
US
I have a few questions about working with bit streams.

how do i output a bit stream
how do i store a bit stream
how do i read in a bit stream

i want to print out and take in and store bits as a bit stream and not just characters that are either one or zero
How would i do this

Thank you very much for trying to help me
 
Where are you trying to input/output this from? The nature of the output will really decide what you want to do. If, for example, you want to send a stream of bits to a serial port, the best bet would be to combine them in sets of 8 and send write that value. Other output forms may require different methodology, but writing out bytes is almost certainly going to be involved.
 
Certainly the easisest way of handling bits is with the STL bitset class. The following code sets up an array of 8-bit bitsets, writes it to a file, reads it in again and prints it out (as character 0,1) to stdout.

#include <iostream>
#include <vector>
#include <bitset>
#include <fstream>

using namespace std;

typedef vector<bitset<8> > tvbs8; // Aarray of 1 byte bitsets

int main(int argc, char* argv[])
{
tvbs8 vbs8(5);
tvbs8::iterator ivbs8;
bool b = false;
int i,j;
unsigned long ul;

// Create bitset setting alternate bits in each byte
for (i = 0; i<vbs8.size(); i++)
{
for (j = 0; j<8; j++)
{
vbs8[j] = b = !b; // Set bit j in byte i alternately
}
}

// Print out our bitset array as char 0,1
for (ivbs8 = vbs8.begin(); ivbs8!=vbs8.end(); ivbs8++) cout << *ivbs8 << endl;

// Write array to binary file
ofstream ofs(&quot;C:\\bitset.bin&quot;,ios_base::binary);
for (ivbs8 = vbs8.begin(); ivbs8!=vbs8.end(); ivbs8++) ofs << (unsigned char)(*ivbs8).to_ulong();
ofs.close();

// Read binary file back into a new bitset array
tvbs8 vbs8in;
ifstream ifs(&quot;C:\\bitset.bin&quot;,ios_base::binary);
while(ifs.good())
{
ul = ifs.get();
if (ifs.good()) vbs8in.push_back(bitset<8>(ul));
}

// Print out bitset array again as char 0,1
for (ivbs8 = vbs8in.begin(); ivbs8!=vbs8in.end(); ivbs8++) cout << *ivbs8 << endl;

return 0;
}

As you can see, you can access the bits (j) in the bytes in an array (i) simply with array[j], which makes bit-handling pretty simple. :) I just can't help it, I like MS...:)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top