kcpmtk/binary.inc

58 lines
1.1 KiB
PHP

type
ByteString = String[2]; { String representing a u8. }
ShortString = 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 : ByteString): Byte;
var
out : Byte = 0;
begin
out := ReadDigit(bstr[1]) shl 4;
out := out + ReadDigit(bstr[2]);
ReadByte := out;
end;