Skip to content

Instantly share code, notes, and snippets.

@Konard
Last active December 17, 2015 01:10
Show Gist options
  • Save Konard/5526810 to your computer and use it in GitHub Desktop.
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.
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