-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathExtendedBinaryReader.cs
88 lines (70 loc) · 1.95 KB
/
ExtendedBinaryReader.cs
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
using System;
using System.IO;
using System.Text;
namespace IO
{
public sealed class ExtendedBinaryReader : BinaryReader
{
public ExtendedBinaryReader(Stream s) : this(s, new UTF8Encoding()) { }
public ExtendedBinaryReader(Stream input, Encoding encoding, bool leaveOpen = false)
: base(input, encoding, leaveOpen) {}
/// <summary>
/// returns an unsigned short from the binary reader
/// </summary>
public ushort ReadOptUInt16()
{
ushort count = 0;
var shift = 0;
while (shift != 21)
{
byte b = ReadByte();
count |= (ushort)((b & sbyte.MaxValue) << shift);
shift += 7;
if ((b & 128) == 0) return count;
}
throw new FormatException("Unable to read the 7-bit encoded unsigned short");
}
/// <summary>
/// returns an integer from the binary reader
/// </summary>
public int ReadOptInt32()
{
var count = 0;
var shift = 0;
while (shift != 35)
{
byte b = ReadByte();
count |= (b & sbyte.MaxValue) << shift;
shift += 7;
if ((b & 128) == 0) return count;
}
throw new FormatException("Unable to read the 7-bit encoded integer");
}
/// <summary>
/// returns a long from the binary reader
/// </summary>
public long ReadOptInt64()
{
long count = 0;
var shift = 0;
while (shift != 70)
{
byte b = ReadByte();
count |= (long)(b & sbyte.MaxValue) << shift;
shift += 7;
if ((b & 128) == 0) return count;
}
throw new FormatException("Unable to read the 7-bit encoded long");
}
/// <summary>
/// returns an ASCII string from the binary reader
/// </summary>
public string ReadAsciiString()
{
int numBytes = ReadOptInt32();
// grab the ASCII characters
// ReSharper disable once AssignNullToNotNullAttribute
return numBytes == 0 ? null : Encoding.ASCII.GetString(ReadBytes(numBytes));
}
}
}