By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,197 Members | 975 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,197 IT Pros & Developers. It's quick & easy.

Convert object to byte[]

P: 18
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.

Expand|Select|Wrap|Line Numbers
  1. private byte[] ObjectToByteArray(Object obj)
  2. {
  3.       if(obj == null)
  4.                return null;
  5.      BinaryFormatter bf = new BinaryFormatter();
  6.      MemoryStream ms = new MemoryStream();
  7.      bf.Serialize(ms, obj);
  8.     return ms.ToArray();
  9.  }
Can anyone help me out as it is a big hindrance for me to proceed further.

Thanks in Advance
Eric Haas.
Dec 18 '08 #1
Share this Question
Share on Google+
2 Replies

Expert 5K+
P: 7,872
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
Dec 18 '08 #2

P: 10
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.

Expand|Select|Wrap|Line Numbers
  1. Class nObj = (Class )obj.
  3.  //you should know the size of the object
  4. byte[] buffer = new byte[MSG_SIZE]; 
  5. int index = 0;
  7. //set the data - insert the data in the right order    
  8. buffer[index] = (byte)nObj.m_entId;
  9. //index is updated, depends on the datatype ( int16 in this example )
  10. index +=2;
  12. buffer[index] = (byte)nObj.m_bTask;
  13. //index is updated, depends on the datatype ( byte in this example )
  14. index += 1;
  16. //you have buffer that holds all the data
  17. return buffer
Good Luck!
Dec 18 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.