Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a class to byte array + C#

Tags:

c#-3.0

How can I convert a Class to byte array in C#. This is a managed one so the following code is failing

int objsize = System.Runtime.InteropServices.Marshal.SizeOf(objTimeSeries3D);
byte[] arr = new byte[objsize];
IntPtr buff = System.Runtime.InteropServices.Marshal.AllocHGlobal(objsize);
System.Runtime.InteropServices.Marshal.StructureToPtr(objTimeSeries3D, buff, true);
System.Runtime.InteropServices.Marshal.Copy(buff, arr, 0, objsize);
System.Runtime.InteropServices.Marshal.FreeHGlobal(buff);

Thanks

like image 353
Newbie Avatar asked Apr 22 '10 08:04

Newbie


People also ask

How do you turn an object into a Bytearray?

Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class. Flush the contents to the stream using the flush() method. Finally, convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.

What is the process used to convert an object to a stream of bytes?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

Can we convert string to byte array in Java?

A String is stored as an array of Unicode characters in Java. To convert it to a byte array, we translate the sequence of characters into a sequence of bytes. For this translation, we use an instance of Charset. This class specifies a mapping between a sequence of chars and a sequence of bytes.


1 Answers

You can use BinaryFormatter. Note that your class must be [Serializable] for this to work.

private byte[] ToByteArray(object source)
{
    var formatter = new BinaryFormatter();
    using (var stream = new MemoryStream())
    {
        formatter.Serialize(stream, source);                
        return stream.ToArray();
    }
}
like image 134
Igal Tabachnik Avatar answered Nov 03 '22 01:11

Igal Tabachnik