Serialize your object into an array of bytes
// Convert an object to a byte array 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(); } // Convert a byte array to an Object private Object ByteArrayToObject(byte[] arrBytes) { MemoryStream memStream = new MemoryStream(); BinaryFormatter binForm = new BinaryFormatter(); memStream.Write(arrBytes, 0, arrBytes.Length); memStream.Seek(0, SeekOrigin.Begin); Object obj = (Object) binForm.Deserialize(memStream); return obj; }
And then use a MemoryStream
to record it as needed
byte[] mData = ObjectToByteArray(myObject); MemoryStream memStream = new MemoryStream(); memStream.write(mData, 0, mData.Length);
EDIT: If you want to write an integer, use
byte[] mData = BitConverter.GetBytes((UInt16)iInteger); memStream.write(mData, 0, mData.Length);
source share