MLIB
Loading...
Searching...
No Matches
bitstream.h
Go to the documentation of this file.
1/*
2 Copyright (c) Mircea Neacsu (2014-2025) Licensed under MIT License.
3 This file is part of MLIB project. See LICENSE file for full license terms.
4*/
5
7
8#pragma once
9#include <iostream>
10
11#if __has_include("defs.h")
12#include "defs.h"
13#endif
14
15namespace mlib {
16
18class bitstream
19{
20public:
21 bitstream (std::iostream& str, unsigned int pack);
22
24 bool read ();
25
27 int read (size_t sz, bool is_signed = false);
28
30 void write (bool val);
31
33 void write (int val, size_t sz);
34
35 void flush ();
36
37protected:
38 const unsigned int packing;
39 std::iostream& s;
40
42 virtual char encode (unsigned char bits);
43
45 virtual unsigned char decode (char chr);
46
47private:
48 unsigned char buffer;
49 int nbits;
50};
51
57inline
58char bitstream::encode (unsigned char bits)
59{
60 return (bits & (1 << packing) - 1);
61}
62
68inline unsigned char bitstream::decode (char chr)
69{
70 return (chr & (1 << packing) - 1);
71}
72
73}; // namespace mlib
Read and write bit fields.
virtual unsigned char decode(char chr)
Decode bit field from a byte.
Definition bitstream.h:68
const unsigned int packing
number of used bits per byte
Definition bitstream.h:38
std::iostream & s
underlining (byte) stream
Definition bitstream.h:39
bitstream(std::iostream &str, unsigned int pack)
Constructor.
Definition bitstream.cpp:26
void write(bool val)
Write a bit to stream.
Definition bitstream.cpp:64
virtual char encode(unsigned char bits)
Encode bit field in a byte.
Definition bitstream.h:58
void flush()
If there are any leftover bits, encode them in one character and write them out to stream.
Definition bitstream.cpp:83
bool read()
Read the next bit.
Definition bitstream.cpp:41