{ binary.pas contains procedures and functions for dealing with binary data. } type BStr = String[2]; { String representing a u8. } WStr = String[4]; { String representing a u16. } BinFile = File of Byte; Procedure ExpandFile(var fil : BinFile; var pos : Integer; pad : Integer); var i : Integer; begin for i := 1 to pad do Write(fil, Byte(0)); pos := FilePos(fil); end; function ValidHexDigit(bval: Byte): Boolean; var IsValid : Boolean; begin IsValid := False; if ((bval >= $30) and (bval <= $39)) then IsValid := True; if ((bval >= $41) and (bval <= $46)) then IsValid := True; if ((bval >= $61) and (bval <= $66)) then IsValid := True; ValidHexDigit := IsValid; end; function ReadDigit(bchr: Char): Byte; var bval : Byte; label exitearly; begin bval := Byte(bchr); if (not ValidHexDigit(bval)) then begin bval := 0; goto exitearly; end; {Normalize downcase digits to upcase digits.} if (bchr >= 'a') then bval := bval xor $20; {Perform the conversion.} if (bchr >= 'A') then bval := bval - $37 else bval := bval - $30; exitearly: ReadDigit := bval; end; function ReadByte(bstr : BStr): Byte; var out : Byte; begin out := ReadDigit(bstr[1]) shl 4; out := out + ReadDigit(bstr[2]); ReadByte := out; end; function ReadWord(bstr : WStr): Integer; var out : Integer; I : Integer; begin out := 0; for I := 1 to 4 do begin out := out shl 4; out := out + Integer(ReadDigit(bstr[I])); end; ReadWord := out; end; function ToDigit(digit : Byte): Char; var c : Char; begin c := Char(0); if (digit < $0A) then c := Char(digit + $30) else if (digit <= $0F) then c := Char(digit + $37); ToDigit := c; end; function WriteByte(bval : Byte): BStr; var s : BStr; begin s := '00'; s[1] := ToDigit(bval shr 4); s[2] := ToDigit(bval and $0F); WriteByte := s; end; function WriteWord(bval : Integer): WStr; var s : WStr; begin s := '0000'; s[1] := ToDigit((bval shr $0C) and $000F); s[2] := ToDigit((bval shr $08) and $000F); s[3] := ToDigit((bval shr $04) and $000F); s[4] := ToDigit(bval and $000F); WriteWord := s; end;