-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBitStream.cpp
101 lines (88 loc) · 2.1 KB
/
BitStream.cpp
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include "stdafx.h"
#include "BitStream.h"
namespace BitSerializing
{
inline void BitStream::Initialize()
{
this->hBitPosition = 1;
this->hBuffer = 0;
this->NeedToRead = true;
this->stream = nullptr;
}
BitStream::BitStream(String ^ Filepath, FileMode mode)
{
this->Initialize();
this->stream = gcnew FileStream(Filepath, mode);
}
BitStream::BitStream(Stream ^ stream)
{
this->Initialize();
this->stream = stream;
}
void BitStream::WriteBits(const unsigned char % BitsHolder, const unsigned char % Amount)
{
signed char ToShift = 9 - (this->hBitPosition + Amount);
if (ToShift > 0)
{
unsigned char value = (BitsHolder << ToShift);
this->hBuffer |= value;
this->hBitPosition += Amount;
}
else if (ToShift == 0)
{
this->hBuffer |= BitsHolder;
stream->WriteByte(this->hBuffer);
this->hBuffer = 0;
this->hBitPosition = 1;
//if (this->hBytePosition >= this->hBuffer->LongLength)
// SetSize(this->hBuffer->LongLength + 10);
}
else
{
ToShift = -ToShift;
WriteBits(BitsHolder >> ToShift, 9 - this->hBitPosition);
WriteBits(BitsHolder & this->AmountBitsMask[ToShift], ToShift);
}
}
unsigned char BitStream::ReadBits(const unsigned char % Amount)
{
unsigned char out;
signed char ToShift = 9 - (this->hBitPosition + Amount);
if (this->NeedToRead)
{
this->hBuffer = stream->ReadByte();
this->NeedToRead = false;
}
if (ToShift < 0)
{
ToShift = -ToShift;
unsigned char I = this->hBitPosition;
out = ReadBits(9 - I) << (Amount - (9 - I));
out |= ReadBits(ToShift);
}
else if (ToShift == 0)
{
out = this->hBuffer & this->AmountBitsMask[Amount];
this->hBitPosition = 1;
this->hBuffer = stream->ReadByte();
}
else
{
out = (this->hBuffer >> ToShift) & this->AmountBitsMask[Amount];
this->hBitPosition += Amount;
}
return out;
}
Stream ^ BitStream::GetBaseStream()
{
return this->stream;
}
void BitStream::Flush()
{
this->stream->Flush();
}
void BitStream::Close()
{
this->stream->Flush();
}
}