Given a FieldInfo object and an object, I need to get the actual bytes representation of the field. I know that the field is either int,Int32,uint,short etc.
How can I get the actual byte representation? BinaryFormatter.Serialize won’t help, since it’ll give me more information than I need (it also records type name etc.). The Marshal class does not seem to have facilities to use bytes array (but maybe I’m missing something).
Thanks
You may also try code like the following if what you actually want is to transfer structures as a byte array:
This converts the given object value to the byte array rawdata. I’ve taken this from code I previously wrote, and you may need to adapt it to your needs to make it actually work. I used it for communication with some hardware with user-defined structures, but it should work for built-in types as well (after all, they’re structures, aren’t they?)
To make structure members properly aligned, use the StructLayout attribute to specify one-byte-alignment:
And then use the MarshalAs attribute as needed for fields, e.g. for inline arrays:
The code to get the structure back from the byte array is something like this:
Of course you’ll need to know the type you want for this to work.
Note that this will not handle endianness for itself. In my project, most fields were one byte only, so it didn’t matter, but for the few fields where it did, I just made the fields private and added public properties that would take care of the endianness (Jon Skeet’s link from a comment to his answer may help you, I wrote some utility functions for this since I needed only few).
When I needed this, I created a Message class that would store the raw value (hence the GetValue method, the code at the top is actually the body of a SetValue method) and had some nice convenience method to get the value formatted etc.