kcpmtk/binary.pas

106 lines
1.9 KiB
Plaintext
Raw Normal View History

2023-10-03 10:07:21 +00:00
type
BStr = String[2]; { String representing a u8. }
WStr = String[4]; { String representing a u16. }
function ValidHexDigit(bval: Byte): Boolean;
var
IsValid : Boolean = False;
begin
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 = 0;
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 - $41) + 10
else
bval := bval - $30;
exitearly:
ReadDigit := bval;
end;
function ReadByte(bstr : BStr): Byte;
var
out : Byte = 0;
begin
out := ReadDigit(bstr[1]) shl 4;
out := out + ReadDigit(bstr[2]);
ReadByte := out;
end;
function ReadWord(bstr : WStr): Integer;
var
out : Integer = 0;
I : Integer = 1;
begin
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 + $41);
ToDigit := c;
end;
function WriteByte(bval : Byte): BStr;
var
s : BStr = '00';
begin
s[1] := ToDigit(bval shr 4);
s[2] := ToDigit(bval and $0F);
WriteByte := s;
end;
function WriteWord(bval : Integer): WStr;
var
s : WStr = '0000';
begin
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;