ByteExtensions.cs
1.7 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
using System;
using System.IO;
namespace UniJSON
{
public static class ByteExtensions
{
public static Byte GetHexDigit(this UInt16 n, int index)
{
return (Byte)(n >> 8 * index & 0xff);
}
public static Byte GetHexDigit(this UInt32 n, int index)
{
return (Byte)(n >> 8 * index & 0xff);
}
public static Byte GetHexDigit(this UInt64 n, int index)
{
return (Byte)(n >> 8 * index & 0xff);
}
public static Byte GetHexDigit(this Int16 n, int index)
{
return (Byte)(n >> 8 * index & 0xff);
}
public static Byte GetHexDigit(this Int32 n, int index)
{
return (Byte)(n >> 8 * index & 0xff);
}
public static Byte GetHexDigit(this Int64 n, int index)
{
return (Byte)(n >> 8 * index & 0xff);
}
public static UInt32 ToUint32(this Single n, Byte[] buffer)
{
if (buffer.Length < 4)
{
throw new ArgumentException();
}
using (var ms = new MemoryStream(buffer))
using (var w = new BinaryWriter(ms))
{
w.Write(n);
}
return BitConverter.ToUInt32(buffer, 0);
}
public static UInt64 ToUint64(this Double n, Byte[] buffer)
{
if (buffer.Length < 8)
{
throw new ArgumentException();
}
using (var ms = new MemoryStream(buffer))
using (var w = new BinaryWriter(ms))
{
w.Write(n);
}
return BitConverter.ToUInt64(buffer, 0);
}
}
}