-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbit_stream.h
66 lines (56 loc) · 1.18 KB
/
bit_stream.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#pragma once
#include <cstdint>
#include <cassert>
class BitStream
{
public:
BitStream(uint8_t *p, int64_t numBytes = INT64_MAX)
: m_p(p)
, m_numBytes(numBytes)
{
Reset();
}
// Gets up to 64 bits at a time
uint64_t GetBits(unsigned int n)
{
assert(n >= 0 && n <= 64);
uint64_t ret = 0;
while (n--)
{
if (m_mask)
{
ret <<= 1;
ret |= (m_byte & m_mask) >> m_pos;
m_mask >>= 1;
m_pos--;
}
if (!m_mask)
{
m_p++;
m_numBytes--;
assert(m_numBytes);
Reset();
}
}
return ret;
}
bool ByteAligned()
{
return m_mask == 0x80; // Or m_pos==7
}
bool MoreDataInByteStream()
{
return m_numBytes != 0;
}
void Reset()
{
m_byte = *m_p;
m_pos = 7; // 0 - 7
m_mask = 0x80;
}
uint8_t *m_p;
uint8_t m_mask;
uint8_t m_pos;
uint8_t m_byte;
int64_t m_numBytes;
};