Trying to create a function that converts objects to byte arrays (without the overhead/metadata things like BinaryFormatter
create). I think I'm happy with the following code except the ability of it to convert UInt32[] arrays and Int32[] arrays to a byte array.
private byte[] ObjectToByteArray(object obj)
{
string dataType = obj.GetType().Name;
switch (dataType)
{
case "Byte[]": // an array of bytes
return (byte[])obj;
case "String": // a null-terminated ASCII string
return Encoding.ASCII.GetBytes((string)obj);
case "UInt16": // an array of unsigned short (16-bit) integers
return BitConverter.GetBytes((ushort)obj);
case "UInt32": // an array of unsigned long (32-bit) integers
return BitConverter.GetBytes((uint)obj);
case "UInt32[]": // an array of pairs of unsigned long (32-bit) integers
//return BitConverter.GetBytes((ushort)obj);
return null;
case "Int32": // an array of signed long (32-bit) integers
return BitConverter.GetBytes((int)obj);
case "Int32[]": // an array of pairs of signed long (32-bit) integers
//return BitConverter.GetBytes((int)obj);
return null;
default:
throw new Exception($"The type of value ({dataType}) is not supported.");
}
}
I was thinking of doing something like a simple for each 4 bytes loop and keep adding them to a byte array but was unsure if that would work or even be the best approach. I'm not even sure my current method is the best approach for what I have already made. Everything I have found on the web seems to confuse me and make my head spin when dealing with converting data types.
public static byte[] ToByteArray<T>(T[] obj) where T : unmanaged
{
var tgt = new byte[Buffer.ByteLength(obj)];
Buffer.BlockCopy(obj, 0, tgt, 0, tgt.Length);
return tgt;
}
Mind Endianess of returned array. It is not safe to serialize it in LittleEndian (windows) and deserialize in BigEndian (linux/mac) and visa-versa. Nor its derivatives like hashes, etc. It's for in-memory use only.
This can be made stable if iterated manually using BinaryPrimitives
. They default to BigEndian for both read/write on all systems.