kcpmtk/binary.pas

128 lines
2.2 KiB
Plaintext
Raw Permalink Normal View History

{
binary.pas contains procedures and functions for dealing
with binary data.
}
2023-10-03 10:07:21 +00:00
type
BStr = String[2]; { String representing a u8. }
WStr = String[4]; { String representing a u16. }
BinFile = File of Byte;
2023-10-04 06:07:58 +00:00
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;
2023-10-03 10:07:21 +00:00
function ValidHexDigit(bval: Byte): Boolean;
var
2023-10-03 23:19:22 +00:00
IsValid : Boolean;
2023-10-03 10:07:21 +00:00
begin
2023-10-03 23:19:22 +00:00
IsValid := False;
2023-10-03 10:07:21 +00:00
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
2023-10-03 23:19:22 +00:00
bval : Byte;
2023-10-03 10:07:21 +00:00
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
2023-10-03 23:19:22 +00:00
bval := bval - $37
2023-10-03 10:07:21 +00:00
else
bval := bval - $30;
exitearly:
ReadDigit := bval;
end;
function ReadByte(bstr : BStr): Byte;
var
2023-10-03 23:19:22 +00:00
out : Byte;
2023-10-03 10:07:21 +00:00
begin
out := ReadDigit(bstr[1]) shl 4;
out := out + ReadDigit(bstr[2]);
ReadByte := out;
end;
function ReadWord(bstr : WStr): Integer;
var
2023-10-03 23:19:22 +00:00
out : Integer;
I : Integer;
2023-10-03 10:07:21 +00:00
begin
2023-10-03 23:19:22 +00:00
out := 0;
2023-10-03 10:07:21 +00:00
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)
2023-10-03 23:19:22 +00:00
else if (digit <= $0F) then
c := Char(digit + $37);
2023-10-03 10:07:21 +00:00
ToDigit := c;
end;
2023-10-04 06:07:58 +00:00
function WriteByte(bval : Byte): BStr;
2023-10-03 10:07:21 +00:00
var
2023-10-03 23:19:22 +00:00
s : BStr;
2023-10-03 10:07:21 +00:00
begin
2023-10-03 23:19:22 +00:00
s := '00';
2023-10-03 10:07:21 +00:00
s[1] := ToDigit(bval shr 4);
s[2] := ToDigit(bval and $0F);
WriteByte := s;
end;
2023-10-04 06:07:58 +00:00
2023-10-03 10:07:21 +00:00
function WriteWord(bval : Integer): WStr;
var
2023-10-03 23:19:22 +00:00
s : WStr;
2023-10-03 10:07:21 +00:00
begin
2023-10-03 23:19:22 +00:00
s := '0000';
2023-10-03 10:07:21 +00:00
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;