-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryWriterMC.cs
67 lines (53 loc) · 1.56 KB
/
BinaryWriterMC.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace MCLib
{
/// <summary>
/// BinaryWriter that automatically converts to big endian if necessary
/// </summary>
public class BinaryWriterMC : BinaryWriter
{
#region Constructor
public BinaryWriterMC(Stream stream)
: base(stream, Encoding.UTF8)
{
}
#endregion
#region Overrides
public override void Write(short value)
{
base.Write(ToBigEndian(BitConverter.GetBytes(value)));
}
public override void Write(int value)
{
base.Write(ToBigEndian(BitConverter.GetBytes(value)));
}
public override void Write(long value)
{
base.Write(ToBigEndian(BitConverter.GetBytes(value)));
}
public override void Write(float value)
{
base.Write(ToBigEndian(BitConverter.GetBytes(value)));
}
public override void Write(double value)
{
base.Write(ToBigEndian(BitConverter.GetBytes(value)));
}
public override void Write(string value)
{
Write((short) Encoding.UTF8.GetByteCount(value));
base.Write(Encoding.UTF8.GetBytes(value));
}
#endregion
#region Helpers
private static byte[] ToBigEndian(IEnumerable<byte> bytes)
{
return BitConverter.IsLittleEndian ? bytes.Reverse().ToArray() : bytes.ToArray();
}
#endregion
}
}