Convert object to byte[]

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Charming12
    New Member
    • Sep 2008
    • 18

    #1

    Convert object to byte[]

    Hi All,

    I am stuck with a unique problem, I have a class whose object i need to convert to a byte[] to send it further.

    I am using microsoft's Binaryformatter to convert object to byte[] as per given below.

    But problem here is that the converted byte[] contains 245 bytes of value instead of 22 what the class actually should contain.

    Code:
    private byte[] ObjectToByteArray(Object obj)
    {
          if(obj == null)
                   return null;
         BinaryFormatter bf = new BinaryFormatter();
         MemoryStream ms = new MemoryStream();
         bf.Serialize(ms, obj);
        return ms.ToArray();
     }
    Can anyone help me out as it is a big hindrance for me to proceed further.

    Thanks in Advance
    Eric Haas.
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    I would guess the extra bytes are there to describe the actual datatype. since you are using a class, extra information must be serialized to dictate what the object was before

    Comment

    • maya7
      New Member
      • Dec 2008
      • 10

      #3
      I had the same problem, I couldn't find an answer, so I used a different way.
      Instead of converting an object, I builded byte[] buffer from the Object's data and sent this buffer. It worked for me.

      [code=cpp]Class nObj = (Class )obj.

      //you should know the size of the object
      byte[] buffer = new byte[MSG_SIZE];
      int index = 0;

      //set the data - insert the data in the right order
      buffer[index] = (byte)nObj.m_en tId;
      //index is updated, depends on the datatype ( int16 in this example )
      index +=2;

      buffer[index] = (byte)nObj.m_bT ask;
      //index is updated, depends on the datatype ( byte in this example )
      index += 1;

      //you have buffer that holds all the data
      return buffer[/code]

      Good Luck!
      Last edited by Frinavale; Dec 18 '08, 05:18 PM. Reason: added [code] tags

      Comment

      Working...