Code4bin Delphi May 2026
TBinaryWriterHelper
uses System.Classes, System.SysUtils;
implementation
procedure WriteSimpleBinary; var Data: TBytes; Stream: TMemoryStream; Value: Integer; begin SetLength(Data, 4); Value := 12345; Move(Value, Data[0], 4); // direct memory copy Stream := TMemoryStream.Create; try Stream.Write(Data[0], Length(Data)); Stream.SaveToFile('output.bin'); finally Stream.Free; end; end; In the style, you would encapsulate this into a reusable TBinaryWriter class. 2. Record Casting (The Delphi Superpower) Delphi records can be read/written directly to streams if they are packed and contain only value types. code4bin delphi
TBinaryWriterHelper = class helper for TStream public procedure WriteInt32(Value: Integer); procedure WriteStringRaw(const Value: string); end; TBinaryWriterHelper uses System
function TBinaryReaderHelper.ReadStringRaw(Length: Integer): string; var Bytes: TBytes; begin SetLength(Bytes, Length); Self.Read(Bytes[0], Length); Result := TEncoding.ASCII.GetString(Bytes); end; procedure WriteStringRaw(const Value: string)
type TBinaryReaderHelper = class helper for TStream private function ReadByte: Byte; inline; function ReadWord: Word; inline; function ReadDWord: Cardinal; inline; public function ReadInt8: ShortInt; function ReadUInt8: Byte; function ReadInt32: Integer; function ReadStringRaw(Length: Integer): string; end;