Last active
December 17, 2015 01:10
-
-
Save Konard/5526810 to your computer and use it in GitHub Desktop.
ByteArrayHelpers is a class that contains useful methods to deal with System.Byte[] type.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.InteropServices; | |
namespace Konard.Helpers | |
{ | |
public static class ByteArrayHelpers | |
{ | |
public static byte[] GetBytes<T>(T obj) | |
where T : struct | |
{ | |
int len = Marshal.SizeOf(obj); | |
byte[] arr = new byte[len]; | |
IntPtr ptr = Marshal.AllocHGlobal(len); | |
Marshal.StructureToPtr(obj, ptr, true); | |
Marshal.Copy(ptr, arr, 0, len); | |
Marshal.FreeHGlobal(ptr); | |
return arr; | |
} | |
public static string GetString(byte[] bytes) | |
{ | |
char[] chars = new char[bytes.Length / sizeof(char)]; | |
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); | |
return new string(chars); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment