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.
BitConverter.GetBytes?BlockCopymethods already submitted as answers?Span<T>or its readonly variant, since it allow you to cast the memory without any copying:MemoryMarshal.Cast<int, byte>(myArray.AsSpan()). But it does have some limitations, so it not always applicable.switchusage: don't switch on.GetType().Name, just switch on the variable itself and use actual types as cases.switch (obj) { case string str: ... case int integer: ... case int[] intArray:and so on.