jbutterfieldAtDiamond
asked on
Serialization of an Int16 returning 52bytes????
I am currently trying to serialize a custom class however I am getting a much larger Byte array than i would expect. In an effort to diagnose the issue I replaced my class with an Int16 object. I would expect the oMemStream.ToArray() to return a byte array of length 2. based on the int16 abc having a value of 0x0706. Instead i am recieving a byte array of length 52.
Can anyone explain how and why i am getting so much data, and two how to get the byte array that actually represents the value of this int16 in such a way that i can apply that knowledge to my custom class.
Thank you.
Can anyone explain how and why i am getting so much data, and two how to get the byte array that actually represents the value of this int16 in such a way that i can apply that knowledge to my custom class.
Thank you.
Int16 abc = 0x0706;
try
{
MemoryStream oMemStream = new MemoryStream();
BinaryFormatter oBinaryFormatter = new BinaryFormatter();
oBinaryFormatter.Serialize(oMemStream, abc);
Byte[] oCommMessage = oMemStream.ToArray();
oMemStream.Close();
}
catch { MessageBox.Show("Error Seralizing ABxCmdMessage"); }
return msgStatus;
the size is larger than expected, because the serialization doesn't just record the bytes, it records the info of the object as well. Meaning information about the object type etc.. is also serialized.
For example, if you deserialize the object again right in your code (which returns type object), if you call GetType() on the returned object, system knows again that it's an Int16.
For example, if you deserialize the object again right in your code (which returns type object), if you call GetType() on the returned object, system knows again that it's an Int16.
ASKER
I have no need to deserialized the object. The Byte[] is going to be send out via a serial com port. Is there a method or parameter that can be set, or a formatter that will not include the adddional information for deserialization?
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
You can also use BitConverter.GetBytes()
ASKER
Why would you use a binary writer vs. a bitconverter, are their advantagages/disadvantages to either?
The actual conversion process would be the same, my preference would be the BinaryWriter, as it's already designed to write to the stream. The bitconverter will work the same for translating into bytes, but you then still need to write them out to the stream, (bytes[], offset, length), which just means a couple more steps.
ASKER