forked from jugglingcats/tachograph-reader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryReader.cs
More file actions
114 lines (92 loc) · 2.48 KB
/
Copy pathBinaryReader.cs
File metadata and controls
114 lines (92 loc) · 2.48 KB
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
114
using System;
using System.IO;
using System.Text;
namespace DataFileReader
{
/// <summary>
/// Simple extension to BinaryReader with convenience methods for reading from tachograph file
/// </summary>
public class CustomBinaryReader : System.IO.BinaryReader
{
// get clock ticks since 1 January 1970
private static readonly long ticks1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0).Ticks;
public CustomBinaryReader(Stream s) : base(s)
{
}
public uint ReadSInt32()
{
// in tachograph file number is little-endian
byte r1=ReadByte();
byte r2=ReadByte();
byte r3=ReadByte();
byte r4=ReadByte();
return (uint) (r4 | r3 << 8 | r2 << 16 | r1 << 24);
}
public uint ReadSInt24()
{
byte r1=ReadByte();
byte r2=ReadByte();
byte r3=ReadByte();
return (uint) (r3 | r2 << 8 | r1 << 16);
}
public uint ReadSInt16()
{
byte r1=ReadByte();
byte r2=ReadByte();
return (uint) (r2 | r1 << 8);
}
public string ReadString(int length)
{
return ReadString(length, Encoding.ASCII);
}
public string ReadString(int length, Encoding enc)
{
byte[] buf=new byte[length];
int amountRead=Read(buf, 0, length);
if ( amountRead != length )
throw new InvalidOperationException("End of file while reading a string");
int nullPos = Array.IndexOf(buf, (byte)0x00);
if (nullPos >= 0 && nullPos < length)
{
Array.Resize(ref buf, nullPos);
}
char[] chars=enc.GetChars(buf);
return new string(chars);
}
public DateTime ReadTimeReal()
{
// the offset is seconds since 1 January 1970
uint offset=ReadSInt32();
// Calculate the absolute number of ticks (100ths of nanoseconds since 0000)
long absTicks=ticks1970 + offset * 10000000L;
// and convert to actual date time class
return new DateTime(absTicks);
}
public uint ReadBCDString(int lengthInBytes)
{
const byte frontMask = 0xF0;
const byte backMask = 0x0F;
if (lengthInBytes > 4)
{
throw new InvalidOperationException("Length too big");
}
byte[] octets = new byte[lengthInBytes];
int amountRead = Read(octets, 0, lengthInBytes);
if (amountRead != lengthInBytes)
{
throw new InvalidOperationException("End of file while reading a string");
}
uint result = 0;
for (int i = 0; i < lengthInBytes; ++i)
{
byte octet = octets[i];
int front = (octet & frontMask) >> 4;
int back = octet & backMask;
result *= 100;
result += (uint) (front * 10);
result += (uint) back;
}
return result;
}
}
}