How to convert byte array to any type

后端 未结 2 817
陌清茗
陌清茗 2020-12-06 04:50

okay guys I\'m seeing question from persons asking how to convert byte arrays to int, string, Stream, etc... and the answers to which

相关标签:
2条回答
  • 2020-12-06 04:55

    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.

    You can try persisting an object to 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. 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.

    0 讨论(0)
  • 2020-12-06 05:04

    c++ template version :

    template<typename T>
    void fromByteArray(T& t, byte *bytes)
    {
      t = *(T*)bytes;
    };
    
    template<typename T>
    byte * toByteArray(T& t) 
    {
      return (byte*)&t;
    };
    
    0 讨论(0)
提交回复
热议问题