Last active
December 16, 2015 09:18
-
-
Save Konard/5411779 to your computer and use it in GitHub Desktop.
ByteArrayExtensions is a class that contains extension-methods for 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 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