-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBitSerializer.cpp
113 lines (95 loc) · 5.38 KB
/
BitSerializer.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
102
103
104
105
106
107
108
109
110
111
112
113
#include "stdafx.h"
#include "BitSerializer.h"
using namespace System;
using namespace System::IO;
namespace BitSerializing
{
inline void BitSerializer::Initialize()
{
this->hBuffer = gcnew array<unsigned char, 1>(0);
this->hBytePosition = 0;
this->hBitPosition = 1;
}
BitSerializer::BitSerializer()
{
this->Initialize();
}
BitSerializer::BitSerializer(const long % AmountBitsToWriteBitsToWrite)
{
this->Initialize();
this->hBuffer = gcnew array<unsigned char, 1>(((8 - (AmountBitsToWriteBitsToWrite % 8)) + AmountBitsToWriteBitsToWrite) / 8);
}
BitSerializer::~BitSerializer()
{
delete[] this->hBuffer;
}
void BitSerializer::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[this->hBytePosition] |= value;
this->hBitPosition += Amount;
}
else if (ToShift == 0)
{
this->hBuffer[this->hBytePosition] |= BitsHolder;
this->hBitPosition = 1;
this->hBytePosition++;
//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 BitSerializer::ReadBits(const unsigned char % Amount)
{
unsigned char out;
signed char ToShift = 9 - (this->hBitPosition + Amount);
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->hBytePosition] & this->AmountBitsMask[Amount];
this->hBitPosition = 1;
this->hBytePosition++;
}
else
{
out = (this->hBuffer[this->hBytePosition] >> ToShift) & this->AmountBitsMask[Amount];
this->hBitPosition += Amount;
}
return out;
}
void BitSerializer::Save(String ^ Filepath)
{
FileStream^ writer = gcnew FileStream(Filepath, FileMode::Create);
writer->Write(this->hBuffer, 0, this->hBuffer->Length);
writer->Close();
}
void BitSerializer::Load(String ^ Filepath)
{
FileStream^ reader = gcnew FileStream(Filepath, FileMode::Open);
this->hBuffer = gcnew array<unsigned char, 1>((int)reader->Length);
reader->Read(this->hBuffer, 0, (int)reader->Length);
reader->Close();
}
void BitSerializer::Reset()
{
this->Initialize();
}
void BitSerializer::ResizeBuffer(const long% BufferSize)
{
Array::Resize(this->hBuffer, BufferSize);
}
}