Created
January 12, 2021 14:06
-
-
Save mjs3339/663ee0224e0cb212f8899ba163de329e to your computer and use it in GitHub Desktop.
GetBytes Primitive, Serializable, Non-Serializable Arrays
This file contains hidden or 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.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Numerics; | |
using System.Reflection; | |
using System.Runtime.InteropServices; | |
using System.Runtime.Serialization.Formatters.Binary; | |
using System.Security; | |
using System.Security.Cryptography; | |
using System.Text; | |
public static class GetBytesClass | |
{ | |
private static readonly int _charSize = sizeof(char); | |
private static readonly BinaryFormatter Formatter = new BinaryFormatter(); | |
private static readonly MonitorActionFuncWrapper _maf = new MonitorActionFuncWrapper(); | |
private static readonly SHA512Managed _hash = new SHA512Managed(); | |
private static readonly object _lo = new object(); | |
public static byte[] GetHashCodeU<T>(this T obj, int bitWidth) | |
{ | |
return _maf.Lock(_hash, () => | |
{ | |
var buf = GetBytes(obj); | |
if (bitWidth < 16 || bitWidth > 512) | |
throw new ArgumentException($"Bit Width {bitWidth} must be between 16 and 512."); | |
return _hash.ComputeHash(buf).SubByte(0, bitWidth >> 3); | |
}); | |
} | |
/// <summary> | |
/// GetBytes central GetType takes 22 Nanoseconds per call | |
/// </summary> | |
[SecurityCritical] | |
public static byte[] GetBytes(this object obj) | |
{ | |
var ltype = obj.GetType(); | |
switch (ltype.Name.Trim('[', ']')) | |
{ | |
case "Byte": | |
return !ltype.IsArray ? new[] {(byte) obj} : (byte[]) obj; | |
case "Boolean": | |
return !ltype.IsArray ? GetBytes((bool) obj) : GetBytes((bool[]) obj); | |
case "SByte": | |
return !ltype.IsArray ? GetBytes((sbyte) obj) : GetBytes((sbyte[]) obj); | |
case "Char": | |
return !ltype.IsArray ? GetBytes((char) obj) : GetBytes((char[]) obj); | |
case "Int16": | |
return !ltype.IsArray ? GetBytes((short) obj) : GetBytes((short[]) obj); | |
case "UInt16": | |
return !ltype.IsArray ? GetBytes((ushort) obj) : GetBytes((ushort[]) obj); | |
case "Int32": | |
return !ltype.IsArray ? GetBytes((int) obj) : GetBytes((int[]) obj); | |
case "UInt32": | |
return !ltype.IsArray ? GetBytes((uint) obj) : GetBytes((uint[]) obj); | |
case "Int64": | |
return !ltype.IsArray ? GetBytes((long) obj) : GetBytes((long[]) obj); | |
case "UInt64": | |
return !ltype.IsArray ? GetBytes((ulong) obj) : GetBytes((ulong[]) obj); | |
case "Single": | |
return !ltype.IsArray ? GetBytes((float) obj) : GetBytes((float[]) obj); | |
case "Double": | |
return !ltype.IsArray ? GetBytes((double) obj) : GetBytes((double[]) obj); | |
case "String": | |
return !ltype.IsArray ? GetBytes((string) obj) : GetBytes((string[]) obj); | |
case "Decimal": | |
return !ltype.IsArray ? GetBytes((decimal) obj) : GetBytes((decimal[]) obj); | |
case "DateTime": | |
return !ltype.IsArray ? GetBytes((DateTime) obj) : GetBytes((DateTime[]) obj); | |
case "SecureString": | |
return !ltype.IsArray ? GetBytes((SecureString) obj) : GetBytes((SecureString[]) obj); | |
case "xIntX": | |
return !ltype.IsArray ? xIntX.GetBytesInt((xIntX) obj) : GetBytes((xIntX[]) obj); | |
case "BigInteger": | |
return !ltype.IsArray ? ((BigInteger) obj).ToByteArray() : GetBytes((BigInteger[]) obj); | |
} | |
if (ltype.IsSerializable) | |
return SerializeObject(obj); | |
return SerializeObjectNonSerial(obj); | |
} | |
public static bool IsValidPrimitive(Type type) | |
{ | |
switch (Type.GetTypeCode(type)) | |
{ | |
case TypeCode.Boolean: | |
case TypeCode.Char: | |
case TypeCode.SByte: | |
case TypeCode.Byte: | |
case TypeCode.Int16: | |
case TypeCode.UInt16: | |
case TypeCode.Int32: | |
case TypeCode.UInt32: | |
case TypeCode.Single: | |
case TypeCode.Object: | |
case TypeCode.DateTime: | |
case TypeCode.String: | |
case TypeCode.Int64: | |
case TypeCode.UInt64: | |
case TypeCode.Double: | |
case TypeCode.Decimal: | |
return true; | |
default: | |
return false; | |
} | |
} | |
/// <summary> | |
/// Get Bytes from a single boolean object | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(bool value) | |
{ | |
return new[] {value ? (byte) 1 : (byte) 0}; | |
} | |
/// <summary> | |
/// Get Bytes from an array of boolean objects | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(bool[] value) | |
{ | |
if (value == null) | |
throw new Exception("GetBytes (bool[]) object cannot be null."); | |
var seed = new byte[0]; | |
return value.Aggregate(seed, (Current, bl) => Current.Add(bl.GetBytes())); | |
} | |
/// <summary> | |
/// Get Bytes from a single byte object | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(byte value) | |
{ | |
return new[] {value}; | |
} | |
/// <summary> | |
/// Get Bytes from a sbyte short object | |
/// (GetBytesClass.cs) | |
/// </summary> | |
[SecuritySafeCritical] | |
private static unsafe byte[] GetBytes(sbyte value) | |
{ | |
var numArray = new byte[1]; | |
fixed (byte* ptr = numArray) | |
{ | |
*(sbyte*) ptr = value; | |
} | |
return numArray; | |
} | |
/// <summary> | |
/// Get Bytes from an array of sbyte objects | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(sbyte[] value) | |
{ | |
if (value == null) | |
throw new Exception("GetBytes (sbyte[]) object cannot be null."); | |
var numArray = new byte[value.Length]; | |
Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length); | |
return numArray; | |
} | |
/// <summary> | |
/// Get Bytes from a single short object | |
/// (GetBytesClass.cs) | |
/// </summary> | |
[SecuritySafeCritical] | |
private static unsafe byte[] GetBytes(short value) | |
{ | |
var numArray = new byte[2]; | |
fixed (byte* ptr = numArray) | |
{ | |
*(short*) ptr = value; | |
} | |
return numArray; | |
} | |
/// <summary> | |
/// Get Bytes from an array of short objects | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(short[] value) | |
{ | |
if (value == null) | |
throw new Exception("GetBytes (short[]) object cannot be null."); | |
var numArray = new byte[value.Length * 2]; | |
Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length); | |
return numArray; | |
} | |
/// <summary> | |
/// Get Bytes from a single unsigned short object | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(ushort value) | |
{ | |
return ((short) value).GetBytes(); | |
} | |
/// <summary> | |
/// Get Bytes from an array of unsigned short objects | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(ushort[] value) | |
{ | |
if (value == null) | |
throw new Exception("GetBytes (ushort[]) object cannot be null."); | |
var numArray = new byte[value.Length * 2]; | |
Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length); | |
return numArray; | |
} | |
/// <summary> | |
/// Get Bytes from a single character object | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(char value) | |
{ | |
return ((short) value).GetBytes(); | |
} | |
/// <summary> | |
/// Get Bytes from an array of character objects | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(char[] value) | |
{ | |
if (value == null) | |
throw new Exception("GetBytes (char[]) object cannot be null."); | |
var numArray = new byte[value.Length * 2]; | |
Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length); | |
return numArray; | |
} | |
/// <summary> | |
/// Get Bytes from a single integer object | |
/// (GetBytesClass.cs) | |
/// </summary> | |
[SecuritySafeCritical] | |
private static unsafe byte[] GetBytes(int value) | |
{ | |
var numArray = new byte[4]; | |
fixed (byte* ptr = numArray) | |
{ | |
*(int*) ptr = value; | |
} | |
return numArray; | |
} | |
/// <summary> | |
/// Get Bytes from a single integer object with index and count | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static byte[] GetBytes(this int value, int sIndex, int count) | |
{ | |
if (count > 4) | |
throw new Exception("Size cannot exceed 4 bytes."); | |
return value.GetBytes().SubArray(sIndex, count); | |
} | |
/// <summary> | |
/// Get Bytes from an array of integer objects | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(int[] value) | |
{ | |
if (value == null) | |
throw new Exception("GetBytes (int[]) object cannot be null."); | |
var numArray = new byte[value.Length * 4]; | |
Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length); | |
return numArray; | |
} | |
/// <summary> | |
/// Get Bytes from a single unsigned integer object | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(uint value) | |
{ | |
return ((int) value).GetBytes(); | |
} | |
public static byte[] GetBytes(this uint value, int sIndex = 0, int count = 4) | |
{ | |
if (count > 4) | |
throw new Exception("Size cannot exceed 4 bytes."); | |
return value.GetBytes().SubArray(sIndex, count); | |
} | |
/// <summary> | |
/// Get Bytes from an array of unsigned integer objects | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(uint[] value) | |
{ | |
if (value == null) | |
throw new Exception("GetBytes (uint[]) object cannot be null."); | |
var numArray = new byte[value.Length * 4]; | |
Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length); | |
return numArray; | |
} | |
/// <summary> | |
/// Get Bytes from a single long object | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static unsafe byte[] GetBytes(long value) | |
{ | |
var numArray = new byte[8]; | |
fixed (byte* ptr = numArray) | |
{ | |
*(long*) ptr = value; | |
} | |
return numArray; | |
} | |
/// <summary> | |
/// Get Bytes from an array of long objects | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(long[] value) | |
{ | |
if (value == null) | |
throw new Exception("GetBytes (long[]) object cannot be null."); | |
var numArray = new byte[value.Length * 8]; | |
Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length); | |
return numArray; | |
} | |
/// <summary> | |
/// Get Bytes from an array of long objects with index and count | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static byte[] GetBytes(long value, int sIndex = 0, int count = 8) | |
{ | |
if (count > 8) | |
throw new Exception("Size cannot exceed 8 bytes."); | |
return value.GetBytes().SubArray(sIndex, count); | |
} | |
/// <summary> | |
/// Get Bytes from a single unsigned long object | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(ulong value) | |
{ | |
return ((long) value).GetBytes(); | |
} | |
public static byte[] GetBytes(this ulong value, int sIndex = 0, int count = 8) | |
{ | |
if (count > 8) | |
throw new Exception("Size cannot exceed 8 bytes."); | |
return ((long) value).GetBytes().SubArray(sIndex, count); | |
} | |
/// <summary> | |
/// Get Bytes from an array of unsigned long objects | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(ulong[] value) | |
{ | |
if (value == null) | |
throw new Exception("GetBytes (ulong[]) object cannot be null."); | |
var numArray = new byte[value.Length * 8]; | |
Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length); | |
return numArray; | |
} | |
/// <summary> | |
/// Get Bytes from a single float object | |
/// (GetBytesClass.cs) | |
/// </summary> | |
[SecuritySafeCritical] | |
private static unsafe byte[] GetBytes(float value) | |
{ | |
return (*(int*) &value).GetBytes(); | |
} | |
/// <summary> | |
/// Get Bytes from an array of float objects | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(float[] value) | |
{ | |
if (value == null) | |
throw new Exception("GetBytes (float[]) object cannot be null."); | |
var numArray = new byte[value.Length * 4]; | |
Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length); | |
return numArray; | |
} | |
/// <summary> | |
/// Get Bytes from a single double object | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static unsafe byte[] GetBytes(double value) | |
{ | |
return (*(long*) &value).GetBytes(); | |
} | |
/// <summary> | |
/// Get Bytes from an array of double objects | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(double[] value) | |
{ | |
if (value == null) | |
throw new Exception("GetBytes (double[]) object cannot be null."); | |
var numArray = new byte[value.Length * 8]; | |
Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length); | |
return numArray; | |
} | |
/// <summary> | |
/// Get Bytes from a single decimal object | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static unsafe byte[] GetBytes(decimal value) | |
{ | |
var array = new byte[16]; | |
fixed (byte* bp = array) | |
{ | |
*(decimal*) bp = value; | |
} | |
return array; | |
} | |
/// <summary> | |
/// Get Bytes from a single DateTime object | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(DateTime value) | |
{ | |
return value.Ticks.GetBytes(); | |
} | |
private static byte[] GetBytes(DateTime[] value) | |
{ | |
if (value == null) | |
throw new Exception("GetBytes (DateTime[]) object cannot be null."); | |
var sodt = 0; | |
unsafe | |
{ | |
sodt = sizeof(DateTime); | |
} | |
var numArray = new byte[value.Length * sodt]; | |
for (var i = 0; i < value.Length; i++) | |
{ | |
var dba = value[i].GetBytes(); | |
Buffer.BlockCopy(dba, 0, numArray, i * sodt, sodt); | |
} | |
return numArray; | |
} | |
/// <summary> | |
/// Get Bytes from an array of decimal objects | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(decimal[] value) | |
{ | |
if (value == null) | |
throw new Exception("GetBytes (decimal[]) object cannot be null."); | |
var numArray = new byte[value.Length * 16]; | |
for (var i = 0; i < value.Length; i++) | |
{ | |
var dba = value[i].GetBytes(); | |
Buffer.BlockCopy(dba, 0, numArray, i * 16, 16); | |
} | |
return numArray; | |
} | |
/// <summary> | |
/// Get Bytes from a single string object using a specified Encoding. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static byte[] GetBytes(this string value, Encoding enc = null) | |
{ | |
if (value == null) | |
throw new Exception("GetBytes (string) object cannot be null."); | |
if (enc == null) | |
return Encoding.ASCII.GetBytes(value); | |
switch (enc) | |
{ | |
case ASCIIEncoding AsciiEncoding: | |
{ | |
return Encoding.ASCII.GetBytes(value); | |
} | |
case UnicodeEncoding UnicodeEncoding: | |
{ | |
var ba = Encoding.Unicode.GetBytes(value); | |
var pre = new byte[] {0xff, 0xfe}; | |
var ra = new byte[ba.Length + 2]; | |
Array.Copy(pre, 0, ra, 0, 2); | |
Array.Copy(ba, 0, ra, 2, ba.Length); | |
return ra; | |
} | |
case UTF32Encoding Utf32Encoding: | |
{ | |
var ba = Encoding.UTF32.GetBytes(value); | |
var pre = new byte[] {0xff, 0xfe, 0, 0}; | |
var ra = new byte[ba.Length + 4]; | |
Array.Copy(pre, 0, ra, 0, 4); | |
Array.Copy(ba, 0, ra, 4, ba.Length); | |
return ra; | |
} | |
case UTF7Encoding Utf7Encoding: | |
{ | |
var ba = Encoding.UTF7.GetBytes(value); | |
var pre = new byte[] {0x2b, 0x2f, 0x76}; | |
var ra = new byte[ba.Length + 3]; | |
Array.Copy(pre, 0, ra, 0, 3); | |
Array.Copy(ba, 0, ra, 3, ba.Length); | |
return ra; | |
} | |
case UTF8Encoding Utf8Encoding: | |
{ | |
var ba = Encoding.UTF8.GetBytes(value); | |
var pre = new byte[] {0xef, 0xbb, 0xbf}; | |
var ra = new byte[ba.Length + 3]; | |
Array.Copy(pre, 0, ra, 0, 3); | |
Array.Copy(ba, 0, ra, 3, ba.Length); | |
return ra; | |
} | |
default: | |
return Encoding.ASCII.GetBytes(value); | |
} | |
} | |
/// <summary> | |
/// Get Bytes from a array of string objects. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static byte[] GetBytes(this string[] value, Encoding enc = null) | |
{ | |
if (value == null) | |
throw new Exception("GetBytes (string[]) object cannot be null."); | |
var numArray = new byte[value.Where(ss => ss != null).Sum(ss => ss.Length)]; | |
var dstOffset = 0; | |
foreach (var str in value) | |
if (str != null) | |
{ | |
Buffer.BlockCopy(str.GetBytes(enc), 0, numArray, dstOffset, str.Length); | |
dstOffset += str.Length; | |
} | |
return numArray; | |
} | |
/// <summary> | |
/// Get Bytes from an array of string objects.?? | |
/// (GetBytesClass.cs) | |
/// </summary> | |
//public static byte[] GetBytes1(this string[] value, Encoding enc = null) | |
//{ | |
// if (value == null) | |
// throw new Exception("GetBytes (string[]) object cannot be null."); | |
// var tb = value[0].GetBytes(enc); | |
// var cs = tb.Length / value[0].Length; | |
// var numArray = new byte[value.Where(ss => ss != null).Sum(ss => ss.Length) * cs]; | |
// var dstOffset = 0; | |
// foreach (var str in value) | |
// if (str != null) | |
// { | |
// var buf = str.GetBytes(enc); | |
// Buffer.BlockCopy(buf, 0, numArray, dstOffset, buf.Length); | |
// dstOffset += buf.Length; | |
// } | |
// return numArray; | |
//} | |
/// <summary> | |
/// Get Bytes from an array of secure string objects | |
/// (GetBytesClass.cs) | |
/// </summary> | |
private static byte[] GetBytes(SecureString[] value) | |
{ | |
if (value == null) | |
throw new Exception("GetBytes (SecureString[]) object cannot be null."); | |
var source = new List<byte[]>(); | |
foreach (var secureString in value) | |
if (secureString != null) | |
{ | |
var byteArray = secureString.GetBytes(); | |
source.Add(byteArray.CloneTo()); | |
} | |
var seed = new byte[source.Sum(ba => ba.Length)]; | |
return source.Aggregate(seed, (Current, ba) => Current.Add(ba)); | |
} | |
/// <summary> | |
/// Get Bytes from a single secure string object using a specified encoding | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static unsafe byte[] GetBytes(this SecureString value, Encoding enc = null) | |
{ | |
if (value == null) | |
throw new Exception("GetBytes (SecureString) object cannot be null."); | |
if (enc == null) | |
enc = Encoding.Default; | |
var maxLength = enc.GetMaxByteCount(value.Length); | |
var bytes = IntPtr.Zero; | |
var str = IntPtr.Zero; | |
try | |
{ | |
bytes = Marshal.AllocHGlobal(maxLength); | |
str = Marshal.SecureStringToBSTR(value); | |
var chars = (char*) str.ToPointer(); | |
var bptr = (byte*) bytes.ToPointer(); | |
var len = enc.GetBytes(chars, value.Length, bptr, maxLength); | |
var _bytes = new byte[len]; | |
for (var i = 0; i < len; ++i) | |
{ | |
_bytes[i] = *bptr; | |
bptr++; | |
} | |
return _bytes; | |
} | |
finally | |
{ | |
if (bytes != IntPtr.Zero) | |
Marshal.FreeHGlobal(bytes); | |
if (str != IntPtr.Zero) | |
Marshal.ZeroFreeBSTR(str); | |
} | |
} | |
private static byte[] GetBytes(xIntX[] value) | |
{ | |
var r = Array.Empty<byte>(); | |
if (value != null) | |
for (var i = 0; i < value.Length; ++i) | |
{ | |
var lb = xIntX.GetBytesInt(value[i]); | |
Array.Resize(ref r, r.Length + lb.Length); | |
r = r.Add(lb); | |
} | |
return r; | |
} | |
private static byte[] GetBytes(BigInteger[] value) | |
{ | |
var r = Array.Empty<byte>(); | |
if (value != null) | |
for (var i = 0; i < value.Length; ++i) | |
{ | |
var lb = GetBytes(value[i]); | |
Array.Resize(ref r, r.Length + lb.Length); | |
r = r.Add(lb); | |
} | |
return r; | |
} | |
private static byte[] GetBytes(BigInteger value) | |
{ | |
return GetBytes(value.Sign).Add(value.ToByteArray()); | |
} | |
/// <summary> | |
/// Gets list of byte arrays from a list of objects of type T. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static List<byte[]> GetBytesObject<T>(this List<T> value) | |
{ | |
return value.Select(o => o.GetBytes()).ToList(); | |
} | |
/// <summary> | |
/// Gets a single object of type T from a byte array. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static T ToObject<T>(this byte[] value) | |
{ | |
if (value == null) | |
throw new Exception("value cannot be null."); | |
using (var stream = new MemoryStream(value)) | |
{ | |
var formatter = new BinaryFormatter(); | |
var result = (T) formatter.Deserialize(stream); | |
return result; | |
} | |
} | |
/// <summary> | |
/// Gets an array of objects of type T from a list of byte arrays. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static T[] ToObject<T>(this List<byte[]> value) | |
{ | |
if (value == null) | |
throw new Exception("value cannot be null."); | |
if (value.Count == 0) | |
throw new Exception("value is empty."); | |
var lst = new List<T>(); | |
foreach (var o in value) | |
lst.Add(o.ToObject<T>()); | |
return lst.ToArray(); | |
} | |
/// <summary> | |
/// Converts a hex string to a byte array. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static byte[] HexToBytes(this string hex) | |
{ | |
if (hex.Length % 2 != 0) | |
throw new Exception($"Incomplete Hex string {hex}"); | |
if (!hex.ContainsOnly("0123456789abcdefABCDEFxX")) | |
throw new Exception("Error: hexNumber cannot contain characters other than 0-9,a-f,A-F, or xX"); | |
hex = hex.ToUpper(); | |
if (hex.IndexOf("0X", StringComparison.OrdinalIgnoreCase) != -1) | |
hex = hex.Substring(2); | |
return Enumerable.Range(0, hex.Length).Where(x => x % 2 == 0).Select(x => Convert.ToByte(hex.Substring(x, 2), 16)).ToArray(); | |
} | |
/// <summary> | |
/// Converts a byte array to a hex string. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static string ToHexString(this byte[] bytes) | |
{ | |
var sb = new StringBuilder(); | |
foreach (var b in bytes) | |
sb.Append(b.ToString("X2")); | |
return sb.ToString(); | |
} | |
/// <summary> | |
/// Converts a hex string to an unsigned long. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static unsafe ulong FromHexStringTo(this string value) | |
{ | |
if (value == null) | |
throw new Exception("Value cannot be null."); | |
if (value.Length == 0) | |
return 0; | |
var ba = value.HexToBytes(); | |
ba = ba.Invert(); | |
if (ba.Length > 8) | |
throw new Exception("Maximum bit width is limited to 64 bits."); | |
var len = ba.Length; | |
switch (len) | |
{ | |
case 1: | |
fixed (byte* ptr = &ba[0]) | |
{ | |
return *ptr; | |
} | |
case 2: | |
fixed (byte* ptr = &ba[0]) | |
{ | |
return *ptr | ((ulong) ptr[1] << 8); | |
} | |
case 3: | |
fixed (byte* ptr = &ba[0]) | |
{ | |
return *ptr | ((ulong) ptr[1] << 8) | ((ulong) ptr[2] << 16); | |
} | |
case 4: | |
fixed (byte* ptr = &ba[0]) | |
{ | |
return *ptr | ((ulong) ptr[1] << 8) | ((ulong) ptr[2] << 16) | ((ulong) ptr[3] << 24); | |
} | |
case 5: | |
fixed (byte* ptr = &ba[0]) | |
{ | |
return *ptr | ((ulong) ptr[1] << 8) | ((ulong) ptr[2] << 16) | ((ulong) ptr[3] << 24) | ((ulong) ptr[4] << 32); | |
} | |
case 6: | |
fixed (byte* ptr = &ba[0]) | |
{ | |
return *ptr | ((ulong) ptr[1] << 8) | ((ulong) ptr[2] << 16) | ((ulong) ptr[3] << 24) | ((ptr[4] | ((ulong) ptr[5] << 8)) << 32); | |
} | |
case 7: | |
fixed (byte* ptr = &ba[0]) | |
{ | |
return *ptr | ((ulong) ptr[1] << 8) | ((ulong) ptr[2] << 16) | ((ulong) ptr[3] << 24) | ((ptr[4] | ((ulong) ptr[5] << 8) | ((ulong) ptr[6] << 16)) << 32); | |
} | |
case 8: | |
fixed (byte* ptr = &ba[0]) | |
{ | |
return *ptr | ((ulong) ptr[1] << 8) | ((ulong) ptr[2] << 16) | ((ulong) ptr[3] << 24) | | |
((ptr[4] | ((ulong) ptr[5] << 8) | ((ulong) ptr[6] << 16) | ((ulong) ptr[7] << 24)) << 32); | |
} | |
default: | |
return 0; | |
} | |
} | |
/// <summary> | |
/// Converts a byte array to a hex string. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static string ToBinaryString(this byte[] bytes) | |
{ | |
var len = bytes.Length; | |
var sb = new StringBuilder(); | |
for (var i = 0; i < len; i++) | |
sb.Append(Convert.ToString(bytes[i], 2).PadLeft(8, '0')); | |
return sb.ToString(); | |
} | |
/// <summary> | |
/// Converts a binary string to an unsigned long. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static ulong FromBinaryStringTo(this string value) | |
{ | |
var reversed = value.Reverse().ToArray(); | |
var num = 0ul; | |
for (var p = 0; p < reversed.Count(); p++) | |
{ | |
if (reversed[p] != '1') | |
continue; | |
num += (ulong) Math.Pow(2, p); | |
} | |
return num; | |
} | |
/// <summary> | |
/// Converts a binary string to a byte array. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static byte[] GetBytesFromBinaryString(this string value) | |
{ | |
if (!value.ContainsOnly("01")) | |
throw new Exception($"Error: Binary string can only contains 0's and 1's. Value:{value}"); | |
var len = value.Length; | |
var bLen = (int) Math.Ceiling(len / 8d); | |
var bytes = new byte[bLen]; | |
var size = 8; | |
for (var i = 1; i <= bLen; i++) | |
{ | |
var idx = len - 8 * i; | |
if (idx < 0) | |
{ | |
size = 8 + idx; | |
idx = 0; | |
} | |
bytes[bLen - i] = Convert.ToByte(value.Substring(idx, size), 2); | |
} | |
return bytes; | |
} | |
/// <summary> | |
/// Converts a byte array to a octal string. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static string ToOctalString(this byte[] value) | |
{ | |
value = value.Invert(); | |
var index = value.Length - 1; | |
var base8 = new StringBuilder(); | |
var rem = value.Length % 3; | |
if (rem == 0) | |
rem = 3; | |
var Base = 0; | |
while (rem != 0) | |
{ | |
Base <<= 8; | |
Base += value[index--]; | |
rem--; | |
} | |
base8.Append(Convert.ToString(Base, 8)); | |
while (index >= 0) | |
{ | |
Base = (value[index] << 16) + (value[index - 1] << 8) + value[index - 2]; | |
base8.Append(Convert.ToString(Base, 8).PadLeft(8, '0')); | |
index -= 3; | |
} | |
return base8.ToString(); | |
} | |
/// <summary> | |
/// Returns a Boolean value converted from the byte at a specified position. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static bool ToBool(this byte[] value, int pos = 0) | |
{ | |
return BitConverter.ToBoolean(value, pos); | |
} | |
/// <summary> | |
/// Returns a Character value converted from the byte at a specified position. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static char ToChar(this byte[] value, int pos = 0) | |
{ | |
return BitConverter.ToChar(value, pos); | |
} | |
public static unsafe byte ToByte(this byte[] value, int pos = 0) | |
{ | |
byte bv; | |
fixed (byte* bp = value) | |
{ | |
var bpp = bp + pos; | |
bv = *bpp; | |
return bv; | |
} | |
} | |
public static unsafe sbyte ToSByte(this byte[] value, int pos = 0) | |
{ | |
fixed (byte* bp = value) | |
{ | |
var ptr = bp + pos; | |
if (pos % 2 == 0) | |
return *(sbyte*) ptr; | |
return (sbyte) *ptr; | |
} | |
} | |
/// <summary> | |
/// Returns a Short value converted from the byte at a specified position. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static short ToShort(this byte[] value, int pos = 0) | |
{ | |
return BitConverter.ToInt16(PadShort(value), pos); | |
} | |
/// <summary> | |
/// Returns a Unsigned Short value converted from the byte at a specified position. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static ushort ToUShort(this byte[] value, int pos = 0) | |
{ | |
return BitConverter.ToUInt16(PadShort(value), pos); | |
} | |
/// <summary> | |
/// Returns a Integer value converted from the byte at a specified position. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static int ToInt(this byte[] value, int pos = 0) | |
{ | |
return BitConverter.ToInt32(PadInt(value), pos); | |
} | |
/// <summary> | |
/// Returns a Unsigned Integer value converted from the byte at a specified position. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static uint ToUInt(this byte[] value, int pos = 0) | |
{ | |
return BitConverter.ToUInt32(PadInt(value), pos); | |
} | |
/// <summary> | |
/// Returns a Long value converted from the byte at a specified position. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static long ToLong(this byte[] value, int pos = 0) | |
{ | |
return BitConverter.ToInt64(PadLong(value), pos); | |
} | |
/// <summary> | |
/// Returns a Unsigned Long value converted from the byte at a specified position. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static ulong ToULong(this byte[] value, int pos = 0) | |
{ | |
return BitConverter.ToUInt64(PadLong(value), pos); | |
} | |
/// <summary> | |
/// Returns a signed 128 Bit value. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static Int128 ToInt128(this byte[] value) | |
{ | |
if (value.Length > 16) | |
throw new ArgumentException($"Value length {value.Length} exceeds limit. {16}"); | |
return new Int128(value); | |
} | |
/// <summary> | |
/// Returns a Unsigned 128 Bit value. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static UInt128 ToUInt128(this byte[] value) | |
{ | |
if (value.Length > 16) | |
throw new ArgumentException($"Value length {value.Length} exceeds limit. {16}"); | |
return new UInt128(value); | |
} | |
/// <summary> | |
/// Returns a signed 256 Bit value. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static Int256 ToInt256(this byte[] value) | |
{ | |
if (value.Length > 32) | |
throw new ArgumentException($"Value length {value.Length} exceeds limit. {32}"); | |
return new Int256(value); | |
} | |
/// <summary> | |
/// Returns a Unsigned 256 Bit value. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static UInt256 ToUInt256(this byte[] value) | |
{ | |
if (value.Length > 32) | |
throw new ArgumentException($"Value length {value.Length} exceeds limit. {32}"); | |
return new UInt256(value); | |
} | |
/// <summary> | |
/// Returns a signed 512 Bit value. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static Int512 ToInt512(this byte[] value) | |
{ | |
if (value.Length > 64) | |
throw new ArgumentException($"Value length {value.Length} exceeds limit. {64}"); | |
return new Int512(value); | |
} | |
/// <summary> | |
/// Returns a Unsigned 512 Bit value. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static UInt512 ToUInt512(this byte[] value) | |
{ | |
if (value.Length > 64) | |
throw new ArgumentException($"Value length {value.Length} exceeds limit. {64}"); | |
return new UInt512(value); | |
} | |
/// <summary> | |
/// Returns a signed 1024 Bit value. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static xIntX ToInt1024(this byte[] value) | |
{ | |
if (value.Length > 128) | |
throw new ArgumentException($"Value length {value.Length} exceeds limit. {128}"); | |
return new xIntX(value, 1024, false); | |
} | |
/// <summary> | |
/// Returns a Unsigned 1024 Bit value. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static xIntX ToUInt1024(this byte[] value) | |
{ | |
if (value.Length > 128) | |
throw new ArgumentException($"Value length {value.Length} exceeds limit. {128}"); | |
return new xIntX(value, 1024, true); | |
} | |
public static xIntX ToxIntX(this byte[] value) | |
{ | |
var bl = value.Length * 8; | |
return new xIntX(value, bl, false); | |
} | |
/// <summary> | |
/// Returns a Float value converted from the byte at a specified position. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static float ToFloat(this byte[] value, int pos = 0) | |
{ | |
return BitConverter.ToSingle(PadInt(value), pos); | |
} | |
/// <summary> | |
/// Returns a Double value converted from the byte at a specified position. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static double ToDouble(this byte[] value, int pos = 0) | |
{ | |
return BitConverter.ToDouble(PadLong(value), pos); | |
} | |
/// <summary> | |
/// Returns a Decimal value converted from the byte at a specified position. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static unsafe decimal ToDecimal(this byte[] value, int pos = 0) | |
{ | |
decimal dv; | |
fixed (byte* bp = value) | |
{ | |
var bpp = bp + pos; | |
dv = *(decimal*) bpp; | |
} | |
return dv; | |
} | |
/// <summary> | |
/// Returns a String value converted from the byte at a specified position. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static string ToString(this byte[] value, int pos = 0) | |
{ | |
return BitConverter.ToString(value, pos); | |
} | |
/// <summary> | |
/// Returns a Secure String value converted from the byte array. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static SecureString ToSecureString(this byte[] value) | |
{ | |
if (value == null) | |
throw new Exception("Value cannot be null."); | |
var securestring = new SecureString(); | |
var asCharA = value.ToCharArray(); | |
foreach (var c in asCharA) | |
securestring.AppendChar(c); | |
return securestring; | |
} | |
/// <summary> | |
/// Returns a Boolean array converted from a byte array. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static bool[] ToBooleanArray(this byte[] value) | |
{ | |
if (value == null) | |
throw new Exception("Value cannot be null."); | |
var arr = new bool[value.Length]; | |
Buffer.BlockCopy(value, 0, arr, 0, value.Length); | |
return arr; | |
} | |
/// <summary> | |
/// Returns a Character array converted from a byte array. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static char[] ToCharArray(this byte[] value) | |
{ | |
if (value == null) | |
throw new Exception("Value cannot be null."); | |
var arr = new char[value.Length]; | |
Buffer.BlockCopy(value, 0, arr, 0, value.Length); | |
return arr; | |
} | |
public static byte[] ToByteArray(this byte[] value, int index = 0, int length = -1) | |
{ | |
if (length == -1) | |
length = value.Length - index; | |
var ba = new byte[length]; | |
Buffer.BlockCopy(value, index, ba, 0, length); | |
return ba; | |
} | |
/// <summary> | |
/// Returns a SByte array converted from a byte array. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static sbyte[] ToSByteArray(this byte[] value) | |
{ | |
if (value == null) | |
throw new Exception("Value cannot be null."); | |
var arr = new sbyte[value.Length]; | |
Buffer.BlockCopy(value, 0, arr, 0, value.Length); | |
return arr; | |
} | |
/// <summary> | |
/// Returns a Short array converted from a byte array. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static short[] ToShortArray(this byte[] value) | |
{ | |
if (value == null) | |
throw new Exception("Value cannot be null."); | |
var arr = new short[value.Length / 2]; | |
Buffer.BlockCopy(value, 0, arr, 0, value.Length); | |
return arr; | |
} | |
/// <summary> | |
/// Returns a Unsigned Short array converted from a byte array. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static ushort[] ToUShortArray(this byte[] value) | |
{ | |
if (value == null) | |
throw new Exception("Value cannot be null."); | |
var arr = new ushort[value.Length / 2]; | |
Buffer.BlockCopy(value, 0, arr, 0, value.Length); | |
return arr; | |
} | |
/// <summary> | |
/// Returns a Integer array converted from a byte array. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static int[] ToIntArray(this byte[] value, bool pad = false) | |
{ | |
if (value == null) | |
throw new Exception("Value cannot be null."); | |
if (pad) | |
value = PadInt(value); | |
var arr = new int[value.Length / 4]; | |
Buffer.BlockCopy(value, 0, arr, 0, value.Length); | |
return arr; | |
} | |
/// <summary> | |
/// Returns a Unsigned Integer array converted from a byte array. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static uint[] ToUIntArray(this byte[] value) | |
{ | |
if (value == null) | |
throw new Exception("Value cannot be null."); | |
var arr = new uint[value.Length / 4]; | |
Buffer.BlockCopy(value, 0, arr, 0, value.Length); | |
return arr; | |
} | |
/// <summary> | |
/// Returns a Long array converted from the byte array. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static long[] ToLongArray(this byte[] value) | |
{ | |
if (value == null) | |
throw new Exception("Value cannot be null."); | |
var arr = new long[value.Length / 8]; | |
Buffer.BlockCopy(value, 0, arr, 0, value.Length); | |
return arr; | |
} | |
/// <summary> | |
/// Returns a Unsigned Long array converted from a byte array. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static ulong[] ToULongArray(this byte[] value) | |
{ | |
if (value == null) | |
throw new Exception("Value cannot be null."); | |
var arr = new ulong[value.Length / 8]; | |
Buffer.BlockCopy(value, 0, arr, 0, value.Length); | |
return arr; | |
} | |
/// <summary> | |
/// Returns a Float array converted from a byte array. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static float[] ToFloatArray(this byte[] value) | |
{ | |
if (value == null) | |
throw new Exception("Value cannot be null."); | |
if (value.Length % 4 != 0) | |
throw new Exception("Byte Object length must be a multiple of 4"); | |
var arr = new List<float>(); | |
for (var i = 0; i < value.Length; i += 4) | |
{ | |
var t = new[] {value[i], value[i + 1], value[i + 2], value[i + 3]}; | |
arr.Add(t.ToFloat()); | |
} | |
return arr.ToArray(); | |
} | |
/// <summary> | |
/// Returns a Double array converted from a byte array. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static double[] ToDoubleArray(this byte[] value) | |
{ | |
if (value == null) | |
throw new Exception("Value cannot be null."); | |
if (value.Length % 8 != 0) | |
throw new Exception("Byte Object length must be a multiple of 8"); | |
var arr = new List<double>(); | |
for (var i = 0; i < value.Length; i += 8) | |
{ | |
var t = new[] | |
{ | |
value[i], value[i + 1], value[i + 2], value[i + 3], value[i + 4], value[i + 5], value[i + 6], | |
value[i + 7] | |
}; | |
arr.Add(t.ToDouble()); | |
} | |
return arr.ToArray(); | |
} | |
/// <summary> | |
/// Returns a decimal array converted from a byte array. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static decimal[] ToDecimalArray(this byte[] value) | |
{ | |
if (value == null) | |
throw new Exception("Value cannot be null."); | |
if (value.Length % 16 != 0) | |
throw new Exception("Byte Object length must be a multiple of 16"); | |
var arr = new List<decimal>(); | |
for (var i = 0; i < value.Length; i += 16) | |
{ | |
var t = new[] | |
{ | |
value[i], value[i + 1], value[i + 2], value[i + 3], value[i + 4], value[i + 5], value[i + 6], | |
value[i + 7], value[i + 8], value[i + 9], value[i + 10], value[i + 11], value[i + 12], | |
value[i + 13], | |
value[i + 14], value[i + 15] | |
}; | |
arr.Add(t.ToDecimal()); | |
} | |
return arr.ToArray(); | |
} | |
/// <summary> | |
/// Returns a Single String converted from the byte array. | |
/// (GetBytesClass.cs) | |
/// </summary> | |
public static string ToSingleString(this byte[] value) | |
{ | |
if (value == null) | |
throw new Exception("Value cannot be null."); | |
var enc = GetEncoding(value); | |
switch (enc) | |
{ | |
case ASCIIEncoding AsciiEncoding: | |
return Encoding.ASCII.GetString(value); | |
case UnicodeEncoding UnicodeEncoding: | |
return Encoding.Unicode.GetString(value); | |
case UTF32Encoding Utf32Encoding: | |
return Encoding.UTF32.GetString(value); | |
case UTF7Encoding Utf7Encoding: | |
return Encoding.UTF7.GetString(value); | |
case UTF8Encoding Utf8Encoding: | |
return Encoding.UTF8.GetString(value); | |
default: | |
return Encoding.ASCII.GetString(value); | |
} | |
} | |
private static Encoding GetEncoding(byte[] Data) | |
{ | |
if (Data == null) | |
throw new Exception("Array cannot be null."); | |
if (Data.Length < 2) | |
return Encoding.Default; | |
if (Data[0] == 0xff && Data[1] == 0xfe) | |
return Encoding.Unicode; | |
if (Data[0] == 0xfe && Data[1] == 0xff) | |
return Encoding.BigEndianUnicode; | |
if (Data.Length < 3) | |
return Encoding.Default; | |
if (Data[0] == 0xef && Data[1] == 0xbb && Data[2] == 0xbf) | |
return Encoding.UTF8; | |
if (Data[0] == 0x2b && Data[1] == 0x2f && Data[2] == 0x76) | |
return Encoding.UTF7; | |
if (Data.Length < 4) | |
return Encoding.Default; | |
if (Data[0] == 0xff && Data[1] == 0xfe && Data[2] == 0 && Data[3] == 0) | |
return Encoding.UTF32; | |
return Encoding.Default; | |
} | |
public static bool ToBool(this string value) | |
{ | |
bool result = default; | |
if (!string.IsNullOrEmpty(value)) | |
bool.TryParse(value, out result); | |
return result; | |
} | |
public static char ToChar(this string value) | |
{ | |
char result = default; | |
if (!string.IsNullOrEmpty(value)) | |
char.TryParse(value, out result); | |
return result; | |
} | |
public static byte ToByte(this string value) | |
{ | |
byte result = default; | |
if (!string.IsNullOrEmpty(value)) | |
byte.TryParse(value, out result); | |
return result; | |
} | |
public static sbyte ToSByte(this string value) | |
{ | |
sbyte result = default; | |
if (!string.IsNullOrEmpty(value)) | |
sbyte.TryParse(value, out result); | |
return result; | |
} | |
public static short ToInt16(this string value) | |
{ | |
short result = 0; | |
if (!string.IsNullOrEmpty(value)) | |
short.TryParse(value, out result); | |
return result; | |
} | |
public static ushort ToUInt16(this string value) | |
{ | |
ushort result = 0; | |
if (!string.IsNullOrEmpty(value)) | |
ushort.TryParse(value, out result); | |
return result; | |
} | |
public static int ToInt32(this string value) | |
{ | |
var result = 0; | |
if (!string.IsNullOrEmpty(value)) | |
int.TryParse(value, out result); | |
return result; | |
} | |
public static uint ToUInt32(this string value) | |
{ | |
uint result = 0; | |
if (!string.IsNullOrEmpty(value)) | |
uint.TryParse(value, out result); | |
return result; | |
} | |
public static long ToInt64(this string value) | |
{ | |
long result = 0; | |
if (!string.IsNullOrEmpty(value)) | |
long.TryParse(value, out result); | |
return result; | |
} | |
public static ulong ToUInt64(this string value) | |
{ | |
ulong result = 0; | |
if (!string.IsNullOrEmpty(value)) | |
ulong.TryParse(value, out result); | |
return result; | |
} | |
public static float ToFloat(this string value) | |
{ | |
float result = 0; | |
if (!string.IsNullOrEmpty(value)) | |
float.TryParse(value, out result); | |
return result; | |
} | |
public static double ToDouble(this string value) | |
{ | |
double result = 0; | |
if (!string.IsNullOrEmpty(value)) | |
double.TryParse(value, out result); | |
return result; | |
} | |
public static decimal ToDecimal(this string value) | |
{ | |
decimal result = 0; | |
if (!string.IsNullOrEmpty(value)) | |
decimal.TryParse(value, out result); | |
return result; | |
} | |
public static bool ToBool(this char value) | |
{ | |
bool result = default; | |
if (!string.IsNullOrEmpty(value.ToString())) | |
bool.TryParse(value.ToString(), out result); | |
return result; | |
} | |
public static byte ToByte(this char value) | |
{ | |
byte result = default; | |
if (!string.IsNullOrEmpty(value.ToString())) | |
byte.TryParse(value.ToString(), out result); | |
return result; | |
} | |
public static sbyte ToSByte(this char value) | |
{ | |
sbyte result = default; | |
if (!string.IsNullOrEmpty(value.ToString())) | |
sbyte.TryParse(value.ToString(), out result); | |
return result; | |
} | |
public static short ToInt16(this char value) | |
{ | |
short result = 0; | |
if (!string.IsNullOrEmpty(value.ToString())) | |
short.TryParse(value.ToString(), out result); | |
return result; | |
} | |
public static ushort ToUInt16(this char value) | |
{ | |
ushort result = 0; | |
if (!string.IsNullOrEmpty(value.ToString())) | |
ushort.TryParse(value.ToString(), out result); | |
return result; | |
} | |
public static int ToInt32(this char value) | |
{ | |
var result = 0; | |
if (!string.IsNullOrEmpty(value.ToString())) | |
int.TryParse(value.ToString(), out result); | |
return result; | |
} | |
public static uint ToUInt32(this char value) | |
{ | |
uint result = 0; | |
if (!string.IsNullOrEmpty(value.ToString())) | |
uint.TryParse(value.ToString(), out result); | |
return result; | |
} | |
public static long ToInt64(this char value) | |
{ | |
long result = 0; | |
if (!string.IsNullOrEmpty(value.ToString())) | |
long.TryParse(value.ToString(), out result); | |
return result; | |
} | |
public static ulong ToUInt64(this char value) | |
{ | |
ulong result = 0; | |
if (!string.IsNullOrEmpty(value.ToString())) | |
ulong.TryParse(value.ToString(), out result); | |
return result; | |
} | |
public static float ToFloat(this char value) | |
{ | |
float result = 0; | |
if (!string.IsNullOrEmpty(value.ToString())) | |
float.TryParse(value.ToString(), out result); | |
return result; | |
} | |
public static double ToDouble(this char value) | |
{ | |
double result = 0; | |
if (!string.IsNullOrEmpty(value.ToString())) | |
double.TryParse(value.ToString(), out result); | |
return result; | |
} | |
public static decimal ToDecimal(this char value) | |
{ | |
decimal result = 0; | |
if (!string.IsNullOrEmpty(value.ToString())) | |
decimal.TryParse(value.ToString(), out result); | |
return result; | |
} | |
private static byte[] PadLong(byte[] ba) | |
{ | |
var s = ba.Length % 8; | |
switch (s) | |
{ | |
case 0: | |
break; | |
case 1: | |
Array.Resize(ref ba, ba.Length + 7); | |
ba[ba.Length - 1] = 0; | |
ba[ba.Length - 2] = 0; | |
ba[ba.Length - 3] = 0; | |
ba[ba.Length - 4] = 0; | |
ba[ba.Length - 5] = 0; | |
ba[ba.Length - 6] = 0; | |
ba[ba.Length - 7] = 0; | |
break; | |
case 2: | |
Array.Resize(ref ba, ba.Length + 6); | |
ba[ba.Length - 1] = 0; | |
ba[ba.Length - 2] = 0; | |
ba[ba.Length - 3] = 0; | |
ba[ba.Length - 4] = 0; | |
ba[ba.Length - 5] = 0; | |
ba[ba.Length - 6] = 0; | |
break; | |
case 3: | |
Array.Resize(ref ba, ba.Length + 5); | |
ba[ba.Length - 1] = 0; | |
ba[ba.Length - 2] = 0; | |
ba[ba.Length - 3] = 0; | |
ba[ba.Length - 4] = 0; | |
ba[ba.Length - 5] = 0; | |
break; | |
case 4: | |
Array.Resize(ref ba, ba.Length + 4); | |
ba[ba.Length - 1] = 0; | |
ba[ba.Length - 2] = 0; | |
ba[ba.Length - 3] = 0; | |
ba[ba.Length - 4] = 0; | |
break; | |
case 5: | |
Array.Resize(ref ba, ba.Length + 3); | |
ba[ba.Length - 1] = 0; | |
ba[ba.Length - 2] = 0; | |
ba[ba.Length - 3] = 0; | |
break; | |
case 6: | |
Array.Resize(ref ba, ba.Length + 2); | |
ba[ba.Length - 1] = 0; | |
ba[ba.Length - 2] = 0; | |
break; | |
case 7: | |
Array.Resize(ref ba, ba.Length + 1); | |
ba[ba.Length - 1] = 0; | |
break; | |
} | |
return ba; | |
} | |
private static byte[] PadInt(byte[] ba) | |
{ | |
var s = ba.Length % 4; | |
switch (s) | |
{ | |
case 0: | |
break; | |
case 1: | |
Array.Resize(ref ba, ba.Length + 3); | |
ba[ba.Length - 1] = 0; | |
ba[ba.Length - 2] = 0; | |
ba[ba.Length - 3] = 0; | |
break; | |
case 2: | |
Array.Resize(ref ba, ba.Length + 2); | |
ba[ba.Length - 1] = 0; | |
ba[ba.Length - 2] = 0; | |
break; | |
case 3: | |
Array.Resize(ref ba, ba.Length + 1); | |
ba[ba.Length - 1] = 0; | |
break; | |
} | |
return ba; | |
} | |
private static byte[] PadShort(byte[] ba) | |
{ | |
var s = ba.Length % 2; | |
switch (s) | |
{ | |
case 0: | |
break; | |
case 1: | |
Array.Resize(ref ba, ba.Length + 1); | |
ba[ba.Length - 1] = 0; | |
break; | |
} | |
return ba; | |
} | |
public static byte[] GetBytesFromString(this string str) | |
{ | |
if (str == null) | |
throw new ArgumentNullException("string cannot be null."); | |
if (str.Length == 0) | |
return Array.Empty<byte>(); | |
var bytes = new byte[str.Length * sizeof(char)]; | |
Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); | |
return bytes; | |
} | |
public static string GetStringFromBytes(this byte[] bytes) | |
{ | |
if (bytes == null) | |
throw new ArgumentNullException("bytes cannot be null."); | |
if (bytes.Length % _charSize != 0) | |
throw new ArgumentException("Invalid bytes length"); | |
if (bytes.Length == 0) | |
return string.Empty; | |
var chars = new char[bytes.Length / sizeof(char)]; | |
Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); | |
return new string(chars); | |
} | |
/// <summary> | |
/// Takes a byte array and converts it to a non-serialized object | |
/// </summary> | |
public static T NonSerialByteArrayToObject<T>(this byte[] data) | |
{ | |
var target = (T) Activator.CreateInstance(typeof(T), null); | |
using (var ms = new MemoryStream(data)) | |
{ | |
byte[] ba = null; | |
var infos = typeof(T).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); | |
foreach (var info in infos) | |
{ | |
ba = new byte[sizeof(int)]; | |
ms.Read(ba, 0, sizeof(int)); | |
var size = BitConverter.ToInt32(ba, 0); | |
ba = new byte[size]; | |
ms.Read(ba, 0, size); | |
var bf = new BinaryFormatter(); | |
using (var ms1 = new MemoryStream(ba)) | |
{ | |
info.SetValue(target, bf.Deserialize(ms1)); | |
} | |
} | |
} | |
return target; | |
} | |
/// <summary> | |
/// Takes a non-serialized object and converts it into a byte array | |
/// </summary> | |
public static byte[] SerializeObjectNonSerial<T>(T obj) | |
{ | |
using (var ms = new MemoryStream()) | |
{ | |
var infos = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); | |
foreach (var info in infos) | |
{ | |
var bf = new BinaryFormatter(); | |
using (var inMStream = new MemoryStream()) | |
{ | |
var v = info.GetValue(obj); | |
if (v != null) | |
{ | |
bf.Serialize(inMStream, v); | |
var ba = inMStream.ToArray(); | |
ms.Write(ba.Length.GetBytes(), 0, sizeof(int)); | |
ms.Write(ba, 0, ba.Length); | |
} | |
} | |
} | |
return ms.ToArray(); | |
} | |
} | |
public static byte[] SerializeObject(object obj) | |
{ | |
using (var stream = new MemoryStream()) | |
{ | |
Formatter.Serialize(stream, obj); | |
return stream.ToArray(); | |
} | |
} | |
public static T DeserializeObject<T>(byte[] bytes) | |
{ | |
using (var stream = new MemoryStream(bytes)) | |
{ | |
var result = (T) Formatter.Deserialize(stream); | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment