How to convert byte array to any type

OK guys, I see a question from people asking how to convert byte arrays to int , string , Stream , etc ... and the answers to which everything is changing, and I personally did not find any satisfactory answers.

So, here are a few types that we want to convert an array of bytes to.

UnityEngine.Font , which can receive ttf data.

UnityEngine.Testure2D , which h can receive data from image files such as .png , .jpg , etc.

How would we convert an array of bytes to string , UnityEngine.Testure2D,UnityEngine.Font , Bitmap , etc ...

The data that fills the byte array must be from a file type whose data can be controlled by the type we want to convert the byte array to?

Is it possible?

Any help would be appreciated.

+5
source share
1 answer

Primitive types are simple because they have a specific representation as an array of bytes. Other objects are not because they may contain things that cannot be stored, for example, file descriptors, links to other objects, etc.

You can try storing the object in a byte array using BinaryFormatter :

 public byte[] ToByteArray<T>(T obj) { if(obj == null) return null; BinaryFormatter bf = new BinaryFormatter(); using(MemoryStream ms = new MemoryStream()) { bf.Serialize(ms, obj); return ms.ToArray(); } } public T FromByteArray<T>(byte[] data) { if(data == null) return default(T); BinaryFormatter bf = new BinaryFormatter(); using(MemoryStream ms = new MemoryStream(data)) { object obj = bf.Deserialize(ms); return (T)obj; } } 

But not all types are serializable. For example, there is no way to β€œstore” a database connection. You can save the information used to create the connection (for example, a connection string), but you cannot save the actual connection object.

+11
source

Source: https://habr.com/ru/post/1233265/


All Articles