-
Notifications
You must be signed in to change notification settings - Fork 7
/
ByteSwapper.cs
98 lines (92 loc) · 3.34 KB
/
ByteSwapper.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
89
90
91
92
93
94
95
96
97
98
namespace Opc.Ua.Edge.Translator
{
class ByteSwapper
{
public static byte[] Swap(byte[] value, bool swapPerRegister = false)
{
if (value.Length == 2)
{
byte[] swappedBytes = new byte[2];
swappedBytes[0] = value[1];
swappedBytes[1] = value[0];
return swappedBytes;
}
if (value.Length == 4)
{
if (swapPerRegister)
{
byte[] swappedBytes = new byte[4];
swappedBytes[2] = value[3];
swappedBytes[3] = value[2];
swappedBytes[0] = value[1];
swappedBytes[1] = value[0];
return swappedBytes;
}
else
{
byte[] swappedBytes = new byte[4];
swappedBytes[0] = value[3];
swappedBytes[1] = value[2];
swappedBytes[2] = value[1];
swappedBytes[3] = value[0];
return swappedBytes;
}
}
if (value.Length == 8)
{
if (swapPerRegister)
{
byte[] swappedBytes = new byte[8];
swappedBytes[6] = value[7];
swappedBytes[7] = value[6];
swappedBytes[4] = value[5];
swappedBytes[5] = value[4];
swappedBytes[2] = value[3];
swappedBytes[3] = value[2];
swappedBytes[0] = value[1];
swappedBytes[1] = value[0];
return swappedBytes;
}
else
{
byte[] swappedBytes = new byte[8];
swappedBytes[0] = value[7];
swappedBytes[1] = value[6];
swappedBytes[2] = value[5];
swappedBytes[3] = value[4];
swappedBytes[4] = value[3];
swappedBytes[5] = value[2];
swappedBytes[6] = value[1];
swappedBytes[7] = value[0];
return swappedBytes;
}
}
// don't swap anything my default
return value;
}
public static ushort Swap(ushort value)
{
return (ushort)(((value & 0x00FF) << 8) |
((value & 0xFF00) >> 8));
}
public static uint Swap(uint value)
{
return ((value & 0x000000FF) << 24) |
((value & 0x0000FF00) << 8) |
((value & 0x00FF0000) >> 8) |
((value & 0xFF000000) >> 24);
}
public static ulong Swap(ulong value)
{
return ((value & 0x00000000000000FFUL) << 56) |
((value & 0x000000000000FF00UL) << 40) |
((value & 0x0000000000FF0000UL) << 24) |
((value & 0x00000000FF000000UL) << 8) |
((value & 0x000000FF00000000UL) >> 8) |
((value & 0x0000FF0000000000UL) >> 24) |
((value & 0x00FF000000000000UL) >> 40) |
((value & 0xFF00000000000000UL) >> 56);
}
}
}