Store Numbers as Binary Example

 

This example shows how to store numbers in binary format to a stream.

Pascal

 

procedure TForm1.Button1Click(Sender: TObject);
var
  LStream: TMemoryStream;
  LFrom: Word;
  LTo: Word;
begin
  // Create an empty stream of any kind
  LStream:= TMemoryStream.Create;
  try
    // Assign a value
    LFrom:= 12345;
    // Write to the stream
    LStream.WriteBuffer(LFrom, SizeOf(Word));
    // Report on the stream size
    ShowMessage('The value ' + IntToStr(LFrom) +
                ' stored in ' + IntToStr(LStream.Size) +
                ' bytes rather than ' +
                IntToStr(Length(IntToStr(LFrom))));
    // Reset the position value ready for reading
    LStream.Position:= 0;
    // Read the value back
    LStream.ReadBuffer(LTo, SizeOf(Word));
    // Confirm the value was saved correctly
    Assert(LTo = LFrom);
  finally
    LStream.Free;
  end;
end;