问题描述
好吧,我看到有人问如何将字节数组转换为 int
、string
、Stream
等...并且答案各不相同,我个人没有找到任何令人满意的答案.
okay guys I'm seeing question from persons asking how to convert byte arrays to int
, string
, Stream
, etc... and the answers to which are all varying and I have personally not found any satisfactory answers.
这里有一些我们想要将字节数组转换为的类型.
So here are some types that we want to convert an array of bytes to.
UnityEngine.Font
可以接收ttf
数据.
UnityEngine.Testure2D
可以从 .png
、.jpg
等图像文件中获取数据...
UnityEngine.Testure2D
which h can take in data from image files like .png
, .jpg
, etc...
我们如何将字节数组转换为 String
、UnityEngine.Testure2D、UnityEngine.Font
、Bitmap
等...
How would we convert a byte array to a String
, UnityEngine.Testure2D,UnityEngine.Font
, Bitmap
, etc...
填充字节数组的数据必须来自一种文件类型,其数据可以由我们要将字节数组转换为的类型进行管理?
The data that populates the byte array must be from a file type whose data can by managed by the type we want to convert the byte array to?
这目前可能吗?
任何帮助将不胜感激.
推荐答案
原始类型很容易,因为它们具有作为字节数组的定义表示.其他对象不是因为它们可能包含无法持久化的东西,例如文件句柄、对其他对象的引用等.
Primitive types are easy because they have a defined representation as a byte array. Other objects are not because they may contain things that cannot be persisted, like file handles, references to other objects, etc.
您可以尝试使用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. There's no way to "store" a connection to a database, for example. You can store the information that's used to create the connection (like the connection string) but you can't store the actual connection object.
这篇关于如何将字节数组转换为任何类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!