I have the following functions to convert primitive array types to byte array so I can convert it to base64 string and then store it somewhere and vice versa, and I'm stuck now because I have to convert decimal type which is not a primitive type. I realise that decimal is basically a struct so I would be converting struct array to byte array, but I've only seen answers using unsafe code and I would like to avoid that if possible. I use Unity and I'm also limited to .NET 2.0
private static string ConvertArrayToBase64<T>(ICollection<T> array) where T : struct
{
if (!typeof(T).IsPrimitive)
throw new InvalidOperationException("Only primitive types are supported.");
int size = Marshal.SizeOf(typeof(T));
var byteArray = new byte[array.Count * size];
Buffer.BlockCopy(array.ToArray(), 0, byteArray, 0, byteArray.Length);
return Convert.ToBase64String(byteArray);
}
private static T[] ConvertBase64ToArray<T>(string base64String) where T : struct
{
if (!typeof(T).IsPrimitive)
throw new InvalidOperationException("Only primitive types are supported.");
var byteArray = Convert.FromBase64String(base64String);
var array = new T[byteArray.Length / Marshal.SizeOf(typeof(T))];
Buffer.BlockCopy(byteArray, 0, array, 0, byteArray.Length);
return array;
}
You should consider using System.IO.BinaryReader
and System.IO.BinaryWriter
. These will enable you to read and write primitives to/from another stream, such as a System.IO.MemoryStream
, which you can then access the binary data and convert to base 64 with Convert.ToBase64String()