In Delphi, one can do the following:
var
ms : TMemoryStream;
i : Integer;
begin
ms := TMemoryStream.Create;
i := 1024;
ms.Write(@i, SizeOf(Integer));
ms.Free;
end;
This will write the memory contents of i into ms.
The .Net version of MemoryStream doesn't have such a feature (neither the managed nor unmanaged versions). I know .Net doesn't work on the same principles as Delphi in this regard.
How does one do this in C#? I am interested in the "best practice" and the fastest methods.
You can Serialize your object to a byte array
// 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 MemoryStream
to write it as wanted
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);
Try using BinaryWriter on top of MemoryStream:
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((int)123);
Note: don't forget to Dispose streams and writers/readers in real code, i.e. by using
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With