ObjectAssociativeArray.cs

Key based, Fast Searchable Values, Multiple Value Arrays.

Key, Values, Values,… All Comparisons are done at the byte level, no need for custom comparator. Keys and all values are searchable, using (Indexed) variable bit width map hashing (Default is 64 Bits, can go up to 512 bits).

using System;
using System.Diagnostics;
[DebuggerDisplay("Count = {" + nameof(Count) + "}")]
[Serializable]
public class ObjectAssociativeArray : MonitorActionFuncWrapper
{
    private ObjectBase   _keys;
    private ObjectBase[] _values;
    public ObjectAssociativeArray() : this(1024)
    {
    }
    public ObjectAssociativeArray(int size, int order = 1)
    {
        _keys   = new ObjectBase(size);
        _values = new ObjectBase[order];
        for (var i = 0; i < order; ++i)
            _values[i] = new ObjectBase(size);
    }
    public int Count => _keys.Count;
    public bool Add(object key, params object[] value)
    {
        if (key == null)
            throw new ArgumentException("Key cannot be null.");
        if (value == null)
            throw new ArgumentException("There must be a least one value.");
        return Lock(this, () =>
        {
            for (var p = 0; p < value.Length; ++p)
                if (_keys.Contains(key) || _values[p].Contains(value[p]))
                    return false;
            var ka = _keys.Add(key);
            var va = false;
            for (var p = 0; p < value.Length; ++p)
            {
                va = _values[p].Add(value[p]);
                if (!va)
                    throw new Exception($"the nth parameter {p} could not be added.");
            }
            return ka && va;
        });
    }
    public (object[] key, object value) GetKeysAndValues(int index)
    {
        return (_keys.ToArray(), _values[index].ToArray());
    }
    #region Generic
    public bool Contains(object key)
    {
        return _keys.Contains(key);
    }
    public bool ContainsValue(object value, int index = 0)
    {
        return _values[index].Contains(value);
    }
    #endregion
}

ObjectDictionary.cs

Object Dictionary Single Associative Array, Searchable Keys and Values

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public class ObjectDictionary : MonitorActionFuncWrapper, IEnumerable<KeyValuePair<object, object>>
{
    public ObjectBase _keys;
    public ObjectBase _values;
    public ObjectDictionary() : this(101)
    {
    }
    public ObjectDictionary(int size)
    {
        _keys   = new ObjectBase(size);
        _values = new ObjectBase(size);
    }
    public ObjectDictionary(IEnumerable<KeyValuePair<object, object>> collection)
    {
        foreach (var kp in collection)
            Add(kp.Key, kp.Value);
    }
    public int Count => _keys.Count;
    public object this[object key]
    {
        get
        {
            var pos = _keys.GetObjectIndex(key, false);
            return pos.idx == -1 ? default : _values[pos.idx];
        }
        set => Add(key, value);
    }
    public object[]                       Values        => _values.ToArray();
    public KeyValuePair<object, object>[] KeyValuePairs => ToArray();
    public object[]                       Keys          => _keys.ToArray();
    public IEnumerator<KeyValuePair<object, object>> GetEnumerator()
    {
        return Lock(this, () =>
        {
            return GetEnum();
        });
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return Lock(this, () =>
        {
            return GetEnum();
        });
    }
    private IEnumerator<KeyValuePair<object, object>> GetEnum()
    {
        for (var i = 0; i < Count; i++)
            yield return new KeyValuePair<object, object>(_keys[i], _values[i]);
    }
    public bool Add(object key, object value)
    {
        return Lock(this, () =>
        {
            if (_keys.Contains(key) || _values.Contains(value))
                return false;
            
            var ka = _keys.Add(key);
            var va = _values.Add(value);

            if (ka || va)
            {
                int a = 1;
            }

            return ka && va;
        });
    }
    public void RemoveKey(object key)
    {
        var kidx = _keys.GetObjectIndex(key, false).idx;
        if (kidx != -1)
        {
            var keys   = _keys;
            var values = _values;
            Clear();
            for (var i = 0; i < keys.Count; ++i)
                if (i != kidx)
                    Add(keys[i], values[i]);
        }
    }
    public void RemoveValue(object value)
    {
        var vidx = _values.GetObjectIndex(value, false).idx;
        if (vidx != -1)
        {
            var keys   = _keys;
            var values = _values;
            Clear();
            for (var i = 0; i < keys.Count; ++i)
                if (i != vidx)
                    Add(keys[i], values[i]);
        }
    }
    public void RebuildLists()
    {
        var keys   = _keys;
        var values = _values;
        Clear();
        for (var i = 0; i < keys.Count; ++i)
            Add(keys[i], values[i]);
    }
    public bool ContainsKey(object key)
    {
        return Lock(this, () =>
        {
            return _keys.Contains(key);
        });
    }
    public bool ContainsValue(object value)
    {
        return Lock(this, () =>
        {
            return _values.Contains(value);
        });
    }
    public int FindKeyIndex(object key)
    {
        return Lock(this, () =>
        {
            return _keys.GetObjectIndex(key, false).idx;
        });
    }
    public int FindValueIndex(object value)
    {
        return Lock(this, () =>
        {
            return _values.GetObjectIndex(value, false).idx;
        });
    }
    public KeyValuePair<object, object>[] ToArray()
    {
        return Lock(this, () =>
        {
            var array = new KeyValuePair<object, object>[Count];
            for (var i = 0; i < Count; i++)
                array[i] = new KeyValuePair<object, object>(_keys[i], _values[i]);
            return array;
        });
    }
    public void Clear()
    {
        Lock(this, () =>
        {
            _keys   = new ObjectBase(_keys.Count);
            _values = new ObjectBase(_values.Count);
        });
    }
}

ObjectIndexer.cs

Sequential Ordering Object Indexer

Pass in an object get back it is sequential index 0…n. Session specific indexing.

Example Classes at the bottom.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
[DebuggerTypeProxy(typeof(HashSetDebugView<>))]
[DebuggerDisplay("Count = {" + nameof(Count) + "}")]
public class ObjectIndexer
{
    private const    int       BitWidth    = 64;
    private const    int       BucketDepth = 3;
    private readonly FNV1a64   hasher;
    internal         int       Count;
    private          long[]    Indices;
    internal         int       Length;
    public           List<int> loopcntlst = new List<int>();
    internal         object[]  Objects;
    private          int       Resizes;
    public ObjectIndexer(int size = 0)
    {
        if (size == 0)
            Length = 1607;
        else
            Length = size;
        Count   = 0;
        Indices = new long[Length * BucketDepth];
        Indices.Fill(-1);
        Objects = new object[Length * BucketDepth];
        Resizes = 0;
        hasher  = new FNV1a64();
    }
    public void Clear()
    {
        Count   = 0;
        Indices = new long[Length   * BucketDepth];
        Objects = new object[Length * BucketDepth];
    }
    private static bool IsPrimitive(object obj)
    {
        switch (Type.GetTypeCode(obj.GetType()))
        {
            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.String:
            case TypeCode.Decimal:
            case TypeCode.DateTime:
            case TypeCode.Int64:
            case TypeCode.UInt64:
            case TypeCode.Double:
                return true;
            default:
                return false;
        }
    }
    private new bool Equals(object x, object y)
    {
        if (x == null || y == null)
            return false;
        var xp = IsPrimitive(x);
        var yp = IsPrimitive(y);
        if (xp != yp)
            return false;
        if (xp && yp)
            return x.Equals(y);
        var xb = x.GetBytes();
        var yb = y.GetBytes();
        if (xb.Length != yb.Length)
            return false;
        return xb.Compare(yb);
    }
    public long FindObject(object obj, out bool found)
    {
        var hashCode = hasher.ComputeHash(obj.GetBytes()).ToLong();
        var StepPos  = (hashCode & long.MaxValue) % Length;
        var loopCnt  = 0;
        while (true)
        {
            loopCnt++;
            if (loopCnt > BucketDepth * 8)
                throw new Exception("Bucket Depth too low.");
            var StartPos = (hashCode & long.MaxValue) % Length * BucketDepth;
            for (var i = StartPos; i < StartPos + BucketDepth; ++i)
            {
                if (Objects[i] == null)
                {
                    found = false;
                    loopcntlst.Add(loopCnt);
                    return i;
                }
                if (Equals(Objects[i], obj))
                {
                    found = true;
                    loopcntlst.Add(loopCnt);
                    return i;
                }
            }
            hashCode += StepPos;
        }
    }
    public bool Contains(object item)
    {
        FindObject(item, out var found);
        return found;
    }
    public long FindIndex(object obj)
    {
        long position;
        bool found;
        if (obj != null)
            position = FindObject(obj, out found);
        else
            throw new ArgumentException("Object cannot be null.");
        return found ? Indices[position] : -1;
    }
    public (long idx, bool found) GetIndex(object obj)
    {
        long position;
        bool found;
        if (obj != null)
            position = FindObject(obj, out found);
        else
            throw new ArgumentException("Object cannot be null.");
        long index;
        if (!found)
        {
            Objects[position] = obj;
            Indices[position] = Count++;
            index             = Indices[position];
            if (Count > Length)
                Resize();
        }
        else
        {
            index = Indices[position];
        }
        return (index, found);
    }
    public bool Add(object obj)
    {
        long position;
        bool found;
        if (obj != null)
            position = FindObject(obj, out found);
        else
            throw new ArgumentException("Object cannot be null.");
        if (!found)
            if (Objects[position] == null)
            {
                Objects[position] = obj;
                Indices[position] = Count++;
                if (Count > Length)
                    Resize();
            }
        return found;
    }
    public int AddRange(IEnumerable<object> items)
    {
        return items.Sum(i => !Add(i) ? 0 : 1);
    }
    private void Resize()
    {
        Resizes++;
        Length += Length * 2; 
        var idxArray = new long[Length * BucketDepth];
        idxArray.Fill(-1);
        var objArray = new object[Length * BucketDepth];
        var cidx     = Indices;
        var cobjs    = Objects;
        Indices = idxArray;
        Objects = objArray;
        for (var i = 0; i < cobjs.Length; ++i)
            if (cobjs[i] != null)
            {
                var position = FindObject(cobjs[i], out var D);
                Objects[position] = cobjs[i];
                Indices[position] = cidx[i];
            }
    }
    public void TrimExcess()
    {
        var hi = 0;
        for (var i = Length * BucketDepth - 1; i >= 0; --i)
            if (Indices[i] != -1)
                break;
            else
                hi = i;
        Array.Resize(ref Objects, hi);
        Array.Resize(ref Indices, hi);
        Length = hi;
        Recalculate();
    }
    private void Recalculate()
    {
        var idxArray = new long[Length * BucketDepth];
        idxArray.Fill(-1);
        var objArray = new object[Length * BucketDepth];
        var cidx     = Indices;
        var cobjs    = Objects;
        Indices = idxArray;
        Objects = objArray;
        for (var i = 0; i < cobjs.Length; ++i)
            if (cobjs[i] != null)
            {
                var position = FindObject(cobjs[i], out var D);
                Objects[position] = cobjs[i];
                Indices[position] = cidx[i];
            }
    }
    public object[] ToArray()
    {
        var array = new object[Count];
        var ptr   = 0;
        for (var i = 0; i < Objects.Length; ++i)
            if (Objects[i] != null)
                array[ptr++] = Objects[i];
        return array;
    }
    public void ExceptWith(IEnumerable<object> other)
    {
        if (other == null)
            throw new Exception("The other set must not be null.");
        if (Count == 0)
            return;
        if (Equals(other, this))
            Clear();
        else
            foreach (var obj in other)
                Remove(obj);
    }
    public void UnionWith(IEnumerable<object> other)
    {
        if (other == null)
            throw new Exception("The other set must not be null.");
        foreach (var obj in other)
            Add(obj);
    }
    public bool Overlaps(IEnumerable<object> other)
    {
        if (other == null)
            throw new Exception("The other set must not be null.");
        return Count != 0 && other.Any(Contains);
    }
    public bool ContainsAllElements(IEnumerable<object> other)
    {
        return other.All(Contains);
    }
    public int RemoveWhere(Predicate<object> pred)
    {
        if (pred == null)
            throw new Exception("The Predicate cannot be null.");
        var matches = 0;
        for (var i = 0; i < Objects.Length; ++i)
            if (Objects[i] != null)
            {
                var obj = Objects[i];
                if (pred(obj) && Remove(obj))
                    ++matches;
            }
        return matches;
    }
    public bool Remove(object oldItem)
    {
        var pos = FindObject(oldItem, out var D);
        if (!D)
            return false;
        Objects[pos] = null;
        Indices[pos] = -1;
        Count--;
        return true;
    }
}
Example HashSet Class Using Indexing.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
[DebuggerTypeProxy(typeof(HashSetDebugView<>))]
[DebuggerDisplay("Count = {" + nameof(Count) + "}")]
[Serializable]
public class TestHashSetObjectIndexerIdx<T> : IEnumerable<T>
{
    private T[]           _array;
    private ObjectIndexer Oi;
    public TestHashSetObjectIndexerIdx(int size = 0)
    {
        Oi     = new ObjectIndexer(size);
        _array = new T[size];
    }
    public int Count => Oi.Count;
    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
        return GetEnumerator();
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
    public T[] ToArray()
    {
        return (T[]) _array.Clone();
    }
    public void Clear()
    {
        Oi.Clear();
        Array.Clear(_array, 0, Oi.Length);
    }
    public bool Add(T item)
    {
        var idx = Oi.GetIndex(item);
        if (_array.Length != Oi.Length)
            Array.Resize(ref _array, Oi.Length);
        _array[idx.idx] = item;
        return idx.found;
    }
    public int AddRange(IEnumerable<T> items)
    {
        return items.Sum(i => !Add(i) ? 0 : 1);
    }
    public bool Contains(T item)
    {
        return Oi.ContainsObject(item);
    }
    public int FindEntry(T item)
    {
        return (int)Oi.FindIndex(item);
    }
    public IEnumerator<T> GetEnumerator()
    {
        return GetEnum();
    }
    public IEnumerator<T> GetEnum()
    {
        for (var i = 0; i < Count; i++)
            if (_array[i] != null)
                yield return _array[i];
    }
}
Example HashSet Class Using Object Indexer as a Base Class:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
[DebuggerTypeProxy(typeof(HashSetDebugView<>))]
[DebuggerDisplay("Count = {" + nameof(Count) + "}")]
[Serializable]
public class TestHashSetObjectIndexer<T> : IEnumerable<T>
{
    private  ObjectIndexer Oi;
    public TestHashSetObjectIndexer(int size = 0)
    {
        Oi = new ObjectIndexer(size);
    }
    public int Count => Oi.Count;
    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
        return GetEnumerator();
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
    public T[] ToArray()
    {
        var newArray = new T[Count];
        var copied   = 0;
        var a        = (object[]) Oi.Objects.Clone();
        for (var i = 0; i < Count && copied < Count; i++)
            if (a[i] != null)
                newArray[copied++] = (T)Convert.ChangeType(a[i], typeof(T));
        return newArray;
    }
    public void Clear()
    {
        Oi.Clear();
    }
    public bool Add(T item)
    {

        return Oi.Add(item);
    }
    public int AddRange(IEnumerable<T> items)
    {
        return items.Sum(i => !Add(i) ? 0 : 1);
    }
    public bool Contains(T item)
    {
        return Oi.ContainsObject(item);
    }
    public int FindEntry(T item)
    {
        var i = Oi.FindObject(item, out var d);
        return d ? (int) i : -1;
    }
    public IEnumerator<T> GetEnumerator()
    {
        return GetEnum();
    }
    public IEnumerator<T> GetEnum()
    {
        var a = (T[]) Oi.Objects.Clone();
        for (var i = 0; i < Count; i++)
            if (a[i] != null)
                yield return (T)Convert.ChangeType(a[i], typeof(T));
    }
}
Example Dictionary Class Using Object Indexer as a Base Class:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
[DebuggerTypeProxy(typeof(HashSetDebugView<>))]
[DebuggerDisplay("Count = {" + nameof(Count) + "}")]
[Serializable]
public class TestDictionaryObjectIndexer<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
{
    private ObjectIndexer _oi;
    private TValue[]      _values;
    public TestDictionaryObjectIndexer(int size = 0)
    {
        _oi     = new ObjectIndexer(size);
        _values = new TValue[size];
    }
    public int      Count  => _oi.Count;
    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
    {
        return GetEnum();
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
    public TKey[] GetKeys()
    {
        var kp   = ToArray();
        var keys = new TKey[Count];
        for (var i = 0; i < Count; ++i)
            keys[i] = kp[i].Key;
        return keys;
    }
    public TValue[] GetValues()
    {
        var kp     = ToArray();
        var values = new TValue[Count];
        for (var i = 0; i < Count; ++i)
            values[i] = kp[i].Value;
        return values;
    }
    public void Clear()
    {
        _oi.Clear();
    }
    public bool Add(TKey key, TValue value)
    {
        var pi = _oi.GetIndex(key);
        if (!pi.found)
        {
            if (_values.Length != _oi.Length)
            {
                var nValues = new TValue[_oi.Length];
                Array.Copy(_values, nValues, _values.Length);
                _values = nValues;
            }
            _values[pi.idx] = value;
            return false;
        }
        _values[pi.idx] = value;
        return true;
    }
    public bool Contains(TKey item)
    {
        return _oi.ContainsObject(item);
    }
    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnum()
    {
        var a = (object[]) _oi.Objects.Clone();
        for (var i = 0; i < Count; i++)
            if (a[i] != null)
            {
                var k = (TKey) Convert.ChangeType(a[i], typeof(TKey));
                var p = _oi.GetIndex(k);
                var v = _values[p.idx];
                yield return new KeyValuePair<TKey, TValue>((TKey) Convert.ChangeType(a[i], typeof(TKey)), v);
            }
    }
    public KeyValuePair<TKey, TValue>[] ToArray()
    {
        var a     = (object[]) _oi.Objects.Clone();
        var array = new KeyValuePair<TKey, TValue>[Count];
        var ptr   = 0;
        for (var i = 0; i < Count; i++)
            if (a[i] != null)
            {
                var k = (TKey) Convert.ChangeType(a[i], typeof(TKey));
                var p = _oi.GetIndex(k);
                var v = _values[p.idx];
                array[ptr++] = new KeyValuePair<TKey, TValue>((TKey) Convert.ChangeType(a[i], typeof(TKey)), v);
            }
        return array;
    }
}

Converters.cs

General Data Converters

Obsolete: Use GetBytesClass.cs instead

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.Text;
public static class Converters
{
    private static readonly int _charSize = sizeof(char);
    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
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this bool value)
    {
        return new[] {value ? (byte) 1 : (byte) 0};
    }
    /// <summary>
    ///     Get Bytes from an array of boolean objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this byte value)
    {
        return new[] {value};
    }
    /// <summary>
    ///     Get Bytes from a sbyte short object
    ///     (Converters.cs)
    /// </summary>
    [SecuritySafeCritical]
    public static unsafe byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    [SecuritySafeCritical]
    public static unsafe byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this ushort value)
    {
        return ((short) value).GetBytes();
    }
    /// <summary>
    ///     Get Bytes from an array of unsigned short objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this char value)
    {
        return ((short) value).GetBytes();
    }
    /// <summary>
    ///     Get Bytes from an array of character objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    [SecuritySafeCritical]
    public static unsafe byte[] GetBytes(this 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
    ///     (Converters.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
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    public static unsafe byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    [SecuritySafeCritical]
    public static unsafe byte[] GetBytes(this float value)
    {
        return (*(int*) &value).GetBytes();
    }
    /// <summary>
    ///     Get Bytes from an array of float objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    public static unsafe byte[] GetBytes(this double value)
    {
        return (*(long*) &value).GetBytes();
    }
    /// <summary>
    ///     Get Bytes from an array of double objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    public static unsafe byte[] GetBytes(this decimal value)
    {
        var array = new byte[16];
        fixed (byte* bp = array)
        {
            *(decimal*) bp = value;
        }
        return array;
    }
    /// <summary>
    ///     Get Bytes from a single DateTime object
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this DateTime value)
    {
        return value.Ticks.GetBytes();
    }
    public static byte[] GetBytes(this 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
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this 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.
    ///     (Converters.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.
    ///     (Converters.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.??
    ///     (Converters.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
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this 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
    ///     (Converters.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);
        }
    }
    public static byte[] GetBytes(this xIntX[] value)
    {
        var r = Array.Empty<byte>();
        if (value != null)
            for (var i = 0; i < value.Length; ++i)
            {
                var lb = value[i].ToByteArray();
                Array.Resize(ref r, r.Length + lb.Length);
                r = r.Add(lb);
            }
        return r;
    }
    public static byte[] GetBytes(this BigInteger[] value)
    {
        var r = Array.Empty<byte>();
        if (value != null)
            for (var i = 0; i < value.Length; ++i)
            {
                var lb = value[i].ToByteArray();
                Array.Resize(ref r, r.Length + lb.Length);
                r = r.Add(lb);
            }
        return r;
    }

    /// <summary>
    ///     Gets list of byte arrays from a list of objects of type T.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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.
    ///     (Converters.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>
    private static byte[] GetBytesObjectNonSerial<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();
        }
    }
}