请高手给个代码看下

解决方案 »

  1.   

    [System.Serializable]
     struct mystruct
     {
     public int a;
     }
    ===============System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
    System.IO.MemoryStream mem = new System.IO.MemoryStream();
    mystruct ms = new mystruct();
    ms.a = 100;
    bf.Serialize( mem , ms );
    mem.Seek( 0 , System.IO.SeekOrigin.Begin );
    byte[] b = new byte[ mem.Length ];
     mem.Read( b , 0 , b.Length  );
      

  2.   

    看这里:http://community.csdn.net/Expert/TopicView1.asp?id=4618430
      

  3.   

    //struct 转化为byte[]
            struct MsgStruct
            {
                 public int type, session, dataLength;
                 public char[] data;
                 public EndPoint clientIPPort;
             }
            private byte[] Struct2Byte(MsgStruct msg)
            {            byte[] bufferData = new byte[12 + msg.dataLength * 2];            byte[] midByte1 = new byte[4];            byte[] midByte2 = new byte[4];
                byte[] midByte3 = new byte[4];
                byte[] midByte4 = new byte[2];            midByte1 = BitConverter.GetBytes(msg.type);
                midByte2 = BitConverter.GetBytes(msg.session);
                midByte3 = BitConverter.GetBytes(msg.dataLength);            for (int i = 0; i < 4; i++)
                {
                    bufferData[i] = midByte1[i];
                    bufferData[i + 4] = midByte2[i];
                    bufferData[i + 8] = midByte3[i];
                }
                for (int i = 0; i < msg.dataLength; i++)
                {
                    midByte4 = BitConverter.GetBytes(msg.data[i]);
                    for (int j = 0; j < 2; j++)
                        bufferData[j + i * 2 + 12] = midByte4[j];
                }
                return bufferData;
            }