MLIB
Loading...
Searching...
No Matches
mlib::bitstream Class Reference

Read and write bit fields. More...

#include <bitstream.h>

Public Member Functions

 bitstream (std::iostream &str, unsigned int pack)
 Constructor.
 
bool read ()
 Read the next bit.
 
int read (size_t sz, bool is_signed=false)
 Read a number of bits.
 
void write (bool val)
 Write a bit to stream.
 
void write (int val, size_t sz)
 Write a number of bits.
 
void flush ()
 If there are any leftover bits, encode them in one character and write them out to stream.
 

Protected Member Functions

virtual char encode (unsigned char bits)
 Encode bit field in a byte.
 
virtual unsigned char decode (char chr)
 Decode bit field from a byte.
 

Protected Attributes

const unsigned int packing
 number of used bits per byte
 
std::iostream & s
 underlining (byte) stream
 

Detailed Description

Read and write bit fields.

This class allows reading and writing of bit fields from or to a byte stream.

It allows for different byte encodings using the protected encode/decode functions.

Constructor & Destructor Documentation

◆ bitstream()

mlib::bitstream::bitstream ( std::iostream & str,
unsigned int pack )

Constructor.

Parameters
strUnderlining iostream
packNumber of bits per byte

Member Function Documentation

◆ decode()

unsigned char mlib::bitstream::decode ( char chr)
inlineprotectedvirtual

Decode bit field from a byte.

The default implementation unpacks the bit field from the LSB of byte.

Parameters
chrencoded byte
Returns
resulting bit field

◆ encode()

char mlib::bitstream::encode ( unsigned char bits)
inlineprotectedvirtual

Encode bit field in a byte.

The default implementation packs the bit field in the LSB of byte.

Parameters
bitsbit field to encode
Returns
encoded byte

◆ read() [1/2]

bool mlib::bitstream::read ( )

Read the next bit.

Read a single bit from stream.

If there are no more bits available in current byte, tries to get a new byte and decodes it using decode() function.

Returns
Bit value
Remarks
All bits read after stream reaches EOF are 0.

◆ read() [2/2]

int mlib::bitstream::read ( size_t sz,
bool sign = false )

Read a number of bits.

Invokes bit read function repeatedly to read all bits.

Parameters
szWidth of bit field
signtrue if first bit should be interpreted as a sign value.
Returns
value (0 to 2sz-1 or -2sz-1 to 2sz-1)

◆ write() [1/2]

void mlib::bitstream::write ( bool val)

Write a bit to stream.

If it has accumulated enough bits calls encode() function to encode them and writes a new byte to underlining stream.

Parameters
valBit value to write

◆ write() [2/2]

void mlib::bitstream::write ( int val,
size_t sz )

Write a number of bits.

Invokes bit write function repeatedly to write each bit.

Parameters
valValue to write (0 to 2sz-1 )
szWidth of bit field

The documentation for this class was generated from the following files: