Link to home
Create AccountLog in
Avatar of jbutterfieldAtDiamond
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.
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;

Open in new window

Avatar of jbutterfieldAtDiamond
jbutterfieldAtDiamond

ASKER

I should mention the goal is that i am trying to develop a method for transmiting a protocol via RS232 Serial. As such i need to transmit a byte array.
Avatar of Snarf0001
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.
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
Avatar of Snarf0001
Snarf0001
Flag of Canada image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
You can also use BitConverter.GetBytes()
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.