Skip to content

Instantly share code, notes, and snippets.

@Konard
Last active December 16, 2015 09:18
Show Gist options
  • Save Konard/5411779 to your computer and use it in GitHub Desktop.
Save Konard/5411779 to your computer and use it in GitHub Desktop.
ByteArrayExtensions is a class that contains extension-methods for System.Byte[] type.
using System;
using System.Runtime.InteropServices;
namespace Konard.Helpers
{
public static class ByteArrayExtensions
{
public static string ToRawString(this byte[] bytes)
{
if (bytes.Length <= 0)
return string.Empty;
char[] chars = new char[bytes.Length / sizeof(char)];
Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
public static T ToStructure<T>(this byte[] bytes)
where T : struct
{
Type structureType = typeof(T);
int len = Marshal.SizeOf(structureType);
IntPtr i = Marshal.AllocHGlobal(len);
Marshal.Copy(bytes, 0, i, len);
T result = (T)Marshal.PtrToStructure(i, structureType);
Marshal.FreeHGlobal(i);
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment