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)
 
bool read ()
 Read the next bit.
 
void write (int val)
 Write a bit to stream.
 
void flush ()
 If there are any leftover bits, encode them in one character and write them out to stream.
 
int mread (unsigned int sz, bool is_signed=false)
 Read a variable number of bits.
 
void mwrite (int val, unsigned int sz)
 Write a variable number of bits.
 

Protected Member Functions

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

Protected Attributes

const unsigned int packing
 
std::iostream & s
 

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.

Remarks
Maximum field width is limited to 32 bits.

Constructor & Destructor Documentation

◆ bitstream()

mlib::bitstream::bitstream ( std::iostream &  str,
unsigned int  pack 
)
Parameters
strUnderlining iostream
packNumber of bits per byte

Member Function Documentation

◆ decode()

void mlib::bitstream::decode ( unsigned char &  bits,
char  chr 
)
inlineprotectedvirtual

Decode bit field from a byte.

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

Parameters
bitsresulting bit field
chrencoded byte

◆ encode()

void mlib::bitstream::encode ( unsigned char  bits,
char &  chr 
)
inlineprotectedvirtual

Encode bit field in a byte.

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

Parameters
bitsbit field to encode
chrencoded byte

◆ mread()

int mlib::bitstream::mread ( unsigned int  sz,
bool  sign = false 
)

Read a variable number of bits.

Invokes read function repeatedly to read all bits.

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

◆ mwrite()

void mlib::bitstream::mwrite ( int  val,
unsigned int  sz 
)

Write a variable number of bits.

Invokes write function repeatedly to write each bit.

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

◆ read()

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.

◆ write()

void mlib::bitstream::write ( int  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

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