-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathByteStuff.cs
41 lines (37 loc) · 1.24 KB
/
ByteStuff.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
using System;
using System.Runtime.InteropServices;
// ReSharper disable SuggestVarOrType_BuiltInTypes
namespace BitMapper
{
public class ByteStuff
{
/// <summary>
/// Get the size of <T> in bytes.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static uint SizeOf<T>() => Convert.ToUInt32(Marshal.SizeOf(typeof(T)));
/// <summary>
/// Get the size of an object in bytes.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static uint GetSize(object obj) => Convert.ToUInt32(Marshal.SizeOf(obj));
/// <summary>
/// Convert a struct/value type to bytes.
/// </summary>
/// <param name="value"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static byte[] GetBytes<T>(T value) where T : struct
{
int size = Marshal.SizeOf(value);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(value, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}
}
}