#include "bitstream.h" static const int BITS_PER_CHAR = 8; // Return bit at position pos in a packed set of bits (pack) int getBit( char pack, int pos ) { return ( pack & ( 1 << pos ) ) ? 1 : 0; } // Set bit at position pos in a packed set of bits (pack) void setBit( char & pack, int pos, int val ) { if( val == 1 ) pack |= ( val << pos ); } // Construct the bit-input stream ibstream::ibstream( istream & is ) : bufferPos( BITS_PER_CHAR ), in( is ) { } // Read one bit int ibstream::readBit( ) { if( bufferPos == BITS_PER_CHAR ) { in.get( buffer ); if( in.eof( ) ) return EOF; bufferPos = 0; } return getBit( buffer, bufferPos++ ); } // Return underlying input stream istream & ibstream::getInputStream( ) const { return in; } // Construct the bit-output stream obstream::obstream( ostream & os ) : bufferPos( 0 ), buffer( 0 ), out( os ) { } // Destructor (writes any bits left in the buffer) obstream::~obstream( ) { flush( ); } // If the buffer is non-empty, write one more char void obstream::flush( ) { if( bufferPos == 0 ) // If buffer is empty return; // Nothing to do out.put( buffer ); // Write the buffer bufferPos = 0; // Reset the position buffer = 0; // Clear the buffer } // Write one bit void obstream::writeBit( int val ) { setBit( buffer, bufferPos++, val ); if( bufferPos == BITS_PER_CHAR ) flush( ); } // Write a vector of bits void obstream::writeBits( const vector & val ) { for( int i = 0; i < val.size( ); i++ ) writeBit( val[ i ] ); } // Return underlying output stream ostream & obstream::getOutputStream( ) const { return out; }