program chxtin;
{$NOMAIN}
{$NOWALKBACK}

{
.stop

File		: DE:[22,310]CHXTIN.PAS
Author		: Peter Stadick
Date		: Jun 6,1989
Edit History	:

       Last Edit: 13-JUN-1989 17:32:12 
}

procedure chxtin(asc:packed array [lo..hi:integer] of char;
		 var bin:integer;
                 var pos:integer); external;
{
 Convert an ascii string of hex digits to an integer. Will start converting
 at pos and will do upto 4 digits. Will stop if end of string is encountered
 or none hex digit is encountered.  Pos will be left at the next position
 to convert.
}

procedure chxtin;

var
  temp,temp2	: packed array [1..4] of char;
  i,j,k		: integer;
  hex_char	: set of char;
  place_value	: array [1..4] of integer;
  

begin
  hex_char := ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];
  { pull out digits }
  temp := '0000';
  i := lo+pos-2;
  j := 0;
  { check that we are still in bounds of string }
  if (i >= hi) or (pos < 1) then
  begin
    pos := hi+1;
    bin := 0;
    if pos < 1 then
      pos := 1;
  end
  else
  begin
    repeat
      i := i + 1;
      j := j + 1;
      temp[j] := asc[i];
    until (i = lo + 3) or
          (i = hi) or
          not (asc[i] in hex_char);

    if not (temp[j] in hex_char) then
    begin
      temp[j] := '0';
      j := j - 1;
    end;    
    pos := lo + j + pos - 1;

    { right justify }
    temp2 := '0000';
    if j > 0 then
    begin
      k := 5;
      for i := j downto 1 do
      begin
        k := k - 1;
        temp2[k] := temp[i];
      end;
    end;

    { convert to decimal }
    bin := 0;
    place_value[1] := 4096;
    place_value[2] := 256;
    place_value[3] := 16;
    place_value[4] := 1;
    for i := 1 to 4 do
      if temp2[i] > '9' then
        bin := bin + ((ord(temp2[i]) - ord('7')) * place_value[i])
      else
        bin := bin + ((ord(temp2[i]) - ord('0')) * place_value[i]);
  end;
end;
