结构数组到字节数组 [英] structure array to byte array

查看:84
本文介绍了结构数组到字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨..

i希望将结构数组转换为字节数组..是否可能???

hi..
i want to convert structure array to byte array..is it possible???

推荐答案

是的,你正在寻找序列化。

引用此命名空间。

Yes, you are looking for serialization.
reference this namespace.
using System.Runtime.Serialization.Formatters.Binary;





使你的测试结构可序列化,就像这样。



Make your test struct serializable, like this.

[Serializable]
    public struct test
    {
        public byte itemcode;
        public string itemname;
        //test* p;
    }



现在可以使用这些方法序列化或反序列化。

Serialize将test数组作为字节数组返回。

deserialize返回你的序列化的bytearray为test数组。


You can now serialize or deserialize by using methods like these.
Serialize returns your "test" array as byte array.
deserialize returns your serialized bytearray as "test" array.

public static class TestSerializer{    
    public static byte[] Serialize(test[] t)
        {
            byte[] result;
            BinaryFormatter bF = new BinaryFormatter();
            using (MemoryStream mS = new MemoryStream())
            {
                bF.Serialize(mS, t);
                mS.Position = 0;
                result = new byte[mS.Length];
                mS.Read(result, 0, result.Length);
            }
            return result;
        }

    public static test[] Deserialize(byte[] buffer)
        {
            test[] result;
            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream mS = new MemoryStream())
            {
                mS.Write(buffer, 0, buffer.Length);
                mS.Position = 0;
             result =   (test[])bf.Deserialize(mS);
            }
            return result;
        }
}
    }



这样称呼它。


Call it like this.

test[] t = new test[200];
byte[] tBin = TestSerializer.Serialize(t);


让我看一下Google [ ^ ] ...


这篇关于结构数组到字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆