[英]How to convert byte array to any type
好吧,伙計們,我看到有人問如何將 byte arrays 轉換為int
、 string
、 Stream
等……答案各不相同,我個人還沒有找到任何令人滿意的答案。
所以這里有一些我們想要將字節數組轉換為的類型。
UnityEngine.Font
可以接收ttf
數據。
UnityEngine.Testure2D
其中 h 可以從.png
、 .jpg
等圖像文件中獲取數據...
我們如何將字節數組轉換為String
、 UnityEngine.Testure2D,UnityEngine.Font
、 Bitmap
等...
填充字節數組的數據必須來自文件類型,其數據可以由我們想要將字節數組轉換為的類型管理?
目前這可能嗎?
任何幫助,將不勝感激。
原始類型很容易,因為它們具有定義的表示形式作為字節數組。 其他對象不是因為它們可能包含無法持久化的內容,例如文件句柄,對其他對象的引用等。
您可以嘗試使用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;
}
}
但並非所有類型都可序列化。 例如,沒有辦法“存儲”與數據庫的連接。 您可以存儲用於創建連接的信息(如連接字符串),但不能存儲實際的連接對象。
c ++模板版本:
template<typename T>
void fromByteArray(T& t, byte *bytes)
{
t = *(T*)bytes;
};
template<typename T>
byte * toByteArray(T& t)
{
return (byte*)&t;
};
您可以在.Net 6中將字節數組反序列化為這樣的類對象。
using System.Text.Json;
using MemoryStream ms = new MemoryStream(bytes);
Examlple ex = JsonSerializer.Deserialize<Example>(ms);
Console.WriteLine(ex.Value);
class Example
{
string Value {get; set; }
}
在 C# 中,您可以很容易地按照以下方法將字節數組轉換為任何 object
byte[] bytesFromBase64 = Convert.FromBase64String(message.Body.ToString());
string stringData = Encoding.UTF8.GetString(bytesFromBase64);
Order order = JsonConvert.DeserializeObject<Order>(stringData);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.