-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntegerExtensions.cs
More file actions
71 lines (56 loc) · 2.24 KB
/
Copy pathIntegerExtensions.cs
File metadata and controls
71 lines (56 loc) · 2.24 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
using System.Buffers.Binary;
namespace Texnomic.Types.Extensions;
public static class IntegerExtensions
{
extension(int Value)
{
public byte[] ToBytes(bool IsBigEndian = true)
{
var Bytes = BitConverter.GetBytes(Value);
if (IsBigEndian && BitConverter.IsLittleEndian) Array.Reverse(Bytes);
return Bytes;
}
/// <summary>Attempts to write the value as a 4-byte payload into <paramref name="Destination"/>.</summary>
public bool TryWriteBytes(Span<byte> Destination, out int BytesWritten, bool IsBigEndian = true)
{
if (Destination.Length < sizeof(int))
{
BytesWritten = 0;
return false;
}
if (IsBigEndian)
BinaryPrimitives.WriteInt32BigEndian(Destination, Value);
else
BinaryPrimitives.WriteInt32LittleEndian(Destination, Value);
BytesWritten = sizeof(int);
return true;
}
public string AsHex(bool Prefixed = true) => Prefixed ? $"0x{Value:x}" : $"{Value:x}";
}
public static string AsHex(this uint Value, bool Prefixed = true) => Prefixed ? $"0x{Value:x}" : $"{Value:x}";
/// <summary>Encodes an unsigned 32-bit integer as a 4-byte buffer with the requested endianness.</summary>
public static byte[] ToBytes(this uint Value, bool IsBigEndian = true)
{
var Bytes = new byte[sizeof(uint)];
if (IsBigEndian)
BinaryPrimitives.WriteUInt32BigEndian(Bytes, Value);
else
BinaryPrimitives.WriteUInt32LittleEndian(Bytes, Value);
return Bytes;
}
/// <summary>Attempts to write an unsigned 32-bit integer into <paramref name="Destination"/>.</summary>
public static bool TryWriteBytes(this uint Value, Span<byte> Destination, out int BytesWritten, bool IsBigEndian = true)
{
if (Destination.Length < sizeof(uint))
{
BytesWritten = 0;
return false;
}
if (IsBigEndian)
BinaryPrimitives.WriteUInt32BigEndian(Destination, Value);
else
BinaryPrimitives.WriteUInt32LittleEndian(Destination, Value);
BytesWritten = sizeof(uint);
return true;
}
}