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.
uses System.Classes, System.SysUtils;
TBinaryReaderHelper
procedure TBinaryWriterHelper.WriteStringRaw(const Value: string); var Bytes: TBytes; begin Bytes := TEncoding.ASCII.GetBytes(Value); Self.Write(Bytes[0], Length(Bytes)); end; code4bin delphi
function SwapEndian32(Value: Cardinal): Cardinal; asm BSWAP EAX end; Many Code4Bin use cases involve reading status bytes where each bit is a flag. uses System
This is quintessential – moving structural code directly to binary. 3. Endianness Handling A hidden trap: Intel CPUs are little-endian. Network protocols are big-endian. A robust Code4Bin module includes swapping functions: Endianness Handling A hidden trap: Intel CPUs are