63 lines
1.3 KiB
C++
63 lines
1.3 KiB
C++
#ifndef BITSTREAM_H
|
|
#define BITSTREAM_H
|
|
|
|
#include <cstdint>
|
|
|
|
template <int maxBytes> class Bitstream {
|
|
|
|
public:
|
|
|
|
inline void reset() {
|
|
bitMask = 128; // start with the MSB
|
|
curIdx = 0; // start with the first byte
|
|
buffer[curIdx] = 0; // initialize all bits with zero
|
|
numBitsUsed = 0; // nothing added
|
|
}
|
|
|
|
inline void addOne() {
|
|
buffer[curIdx] |= (0xFF & bitMask);
|
|
bitMask >>= 1;
|
|
++numBitsUsed;
|
|
checkNextByte();
|
|
}
|
|
|
|
inline void addZero() {
|
|
bitMask >>= 1;
|
|
++numBitsUsed;
|
|
checkNextByte();
|
|
}
|
|
|
|
const uint8_t* getData() const {
|
|
return buffer;
|
|
}
|
|
|
|
/** number of used bits */
|
|
inline uint16_t getNumBits() const {
|
|
return numBitsUsed;
|
|
}
|
|
|
|
/** number of used bytes. rounded-up to multiples of 8-bits */
|
|
inline uint8_t getNumBytes() const {
|
|
return (numBitsUsed - 1) / 8 + 1;
|
|
}
|
|
|
|
private:
|
|
|
|
/** received 8 bits? byte complete? -> next one */
|
|
inline void checkNextByte() {
|
|
if(bitMask == 0) {
|
|
bitMask = 128; // start with the MSB
|
|
++curIdx; // next byte
|
|
buffer[curIdx] = 0; // initialize all bits with zero
|
|
}
|
|
}
|
|
|
|
uint16_t numBitsUsed = 0;
|
|
uint8_t buffer[maxBytes]; //buffer containing received bits
|
|
uint8_t curIdx = 0; //index pointing to the byte currently selected within the buffer
|
|
uint8_t bitMask = 128; //mask for the next bit to write
|
|
|
|
};
|
|
|
|
#endif // BITSTREAM_H
|