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
19{
20public:
21 bitstream (std::iostream& str, unsigned int pack);
22
23 bool read ();
24 void write (int val);
25 void flush ();
26
28 int mread (unsigned int sz, bool is_signed = false);
29
31 void mwrite (int val, unsigned int sz);
32
33protected:
34 const unsigned int packing;
35 std::iostream& s;
36
38 virtual void encode (unsigned char bits, char& chr);
39
41 virtual void decode (unsigned char& bits, char chr);
42
43private:
44 unsigned char buffer;
45 int nbits;
46};
47
53inline void bitstream::encode (unsigned char bits, char& chr)
54{
55 chr = (bits & (1 << packing) - 1);
56}
57
63inline void bitstream::decode (unsigned char& bits, char chr)
64{
65 bits = (chr & (1 << packing) - 1);
66}
67
68}; // namespace mlib
int mread(unsigned int sz, bool is_signed=false)
Read a variable number of bits.
Definition bitstream.cpp:121
bitstream(std::iostream &str, unsigned int pack)
Definition bitstream.cpp:26
void write(int val)
Write a bit to stream.
Definition bitstream.cpp:64
virtual void decode(unsigned char &bits, char chr)
Decode bit field from a byte.
Definition bitstream.h:63
virtual void encode(unsigned char bits, char &chr)
Encode bit field in a byte.
Definition bitstream.h:53
void mwrite(int val, unsigned int sz)
Write a variable number of bits.
Definition bitstream.cpp:103
void flush()
If there are any leftover bits, encode them in one character and write them out to stream.
Definition bitstream.cpp:84
bool read()
Read the next bit.
Definition bitstream.cpp:41