I am using Convert an array of different value types to a byte array solution for my objects to byte array conversion.
But I have a small issue that causes a big problem.
There are "byte" type of data in mids of object[], I don't know how to keep "byte" as is. I need keep same bytes-length before and after.
I tried add "byte" type into the dictionary like this:
private static readonlyDictionary<Type, Func<object, byte[]>> Converters =
    new Dictionary<Type, Func<object, byte[]>>()
{
    { typeof(byte), o => BitConverter.GetBytes((byte) o) },
    { typeof(int), o => BitConverter.GetBytes((int) o) },
    { typeof(UInt16), o => BitConverter.GetBytes((UInt16) o) },
    ...
};
public static void ToBytes(object[] data, byte[] buffer)
{
    int offset = 0;
    foreach (object obj in data)
    {
        if (obj == null)
        {
            // Or do whatever you want
            throw new ArgumentException("Unable to convert null values");
        }
        Func<object, byte[]> converter;
        if (!Converters.TryGetValue(obj.GetType(), out converter))
        {
            throw new ArgumentException("No converter for " + obj.GetType());
        }
        byte[] obytes = converter(obj);
        Buffer.BlockCopy(obytes, 0, buffer, offset, obytes.Length);
        offset += obytes.Length;
    }
}
there is no syntext complaining, but I traced this code, after the program executed
byte[] obytes = converter(obj);
the original "byte" becomes byte[2].
What happens here? How to keep byte value authentic in this solution?
Thanks!
There is no BitConverter.GetBytes overload that takes a byte, so your code:
BitConverter.GetBytes((byte) o)
Is being implicitly expanded into the nearest match: BitConverter.GetBytes(short) (Int16), resulting in two bytes. All you need to do is return a single-element byte array, e.g. like this:
{ typeof(byte), o => new[] { (byte) o } }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With