Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
BitWriter.cs
1using System;
2using System.IO;
3
5{
9 public class BitWriter : IDisposable
10 {
11 private MemoryStream output;
12 private byte current;
13 private int bits;
14 private int length;
15
19 public BitWriter()
20 {
21 this.output = new MemoryStream();
22 this.current = 0;
23 this.bits = 0;
24 this.length = 0;
25 }
26
30 public void Dispose()
31 {
32 this.output?.Dispose();
33 this.output = null;
34 }
35
40 public void WriteBit(bool Bit)
41 {
42 if (Bit)
43 this.current |= (byte)(1 << (7 - this.bits));
44
45 if (++this.bits >= 8)
46 {
47 this.output.WriteByte(this.current);
48 this.length++;
49 this.bits = 0;
50 this.current = 0;
51 }
52 }
53
59 public void WriteBits(uint Value, int NrBits)
60 {
61 if (NrBits < 32)
62 Value <<= (32 - NrBits);
63
64 int c;
65
66 while (NrBits > 0)
67 {
68 c = 8 - this.bits;
69 if (c > NrBits)
70 c = NrBits;
71
72 this.current |= (byte)(Value >> (24 + this.bits));
73 Value <<= c;
74 NrBits -= c;
75 this.bits += c;
76
77 if (this.bits >= 8)
78 {
79 this.output.WriteByte(this.current);
80 this.length++;
81 this.bits = 0;
82 this.current = 0;
83 }
84 }
85 }
86
90 public void Flush()
91 {
92 if (this.bits > 0)
93 {
94 this.output.WriteByte(this.current);
95 this.length++;
96 this.bits = 0;
97 this.current = 0;
98 }
99 }
100
106 public void Pad(int MaxLength, params byte[] PaddingBytes)
107 {
108 int i = 0;
109 int c = PaddingBytes.Length;
110
111 if (c == 0)
112 throw new ArgumentException("Missing padding bytes.", nameof(PaddingBytes));
113
114 this.Flush();
115 while (this.length < MaxLength)
116 {
117 this.output.WriteByte(PaddingBytes[i++]);
118 this.length++;
119 if (i >= c)
120 i = 0;
121 }
122 }
123
128 public byte[] ToArray()
129 {
130 this.Flush();
131 return this.output.ToArray();
132 }
133
137 public int TotalBits => (this.length << 3) + this.bits;
138 }
139}
Writes a sequence of bits (Most significant bits first).
Definition: BitWriter.cs:10
void WriteBit(bool Bit)
Writes a bit to the output.
Definition: BitWriter.cs:40
void Pad(int MaxLength, params byte[] PaddingBytes)
Pads the output with padding bytes.
Definition: BitWriter.cs:106
byte[] ToArray()
Returns a byte-array of serialized bits.
Definition: BitWriter.cs:128
BitWriter()
Writes a sequence of bits (Most significant bits first).
Definition: BitWriter.cs:19
void WriteBits(uint Value, int NrBits)
Writes several bits to the output stream.
Definition: BitWriter.cs:59
void Dispose()
IDisposable.Dispose
Definition: BitWriter.cs:30
int TotalBits
Total number of bits written.
Definition: BitWriter.cs:137
void Flush()
Flushes any remaining bits to the output.
Definition: BitWriter.cs:90