Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# convert object[ ] into byte[ ], but how to keep byte object as byte?

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!

like image 788
Kai Mon Avatar asked Aug 02 '13 20:08

Kai Mon


1 Answers

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 } }
like image 168
Tim S. Avatar answered Oct 21 '22 07:10

Tim S.