Utils package

Sooner or later you need more functions than supplied by the maker of the compiler. MHC produce the bulk of the general purpose functions. You create your own functions, building further upon the defaults. This topic is about the Utils library in which I will store my new functions.
Expect to find the following functions:


DEFINITION MODULE

This is what C coders and such refer to as the header file. Of course the DEFINITION MODULE is more than that. It is a function prototyping framwork that lists all public properties of a library.

DEFINITION MODULE Utils;

TYPE	Identifier	= ARRAY [0..63] OF CHAR;

PROCEDURE CardToHex (c : LONGCARD; VAR str : Identifier; l : CARDINAL);

(* Convert any kind of CARDINAL to a Hexadecimal string of length 'l'.
   Leading zero's are standard.
   *)

END Utils.
   
That's all! A TYPE which I use a lot is defined and then the function prototype of the function is given, together with a comment to describe what it does. This is the place to notice what a function does. The MOD file is not necessarily supplied to the customer.


IMPLEMENTATION MODULE

And this is how the functions, prototyped in the DEFINITION MODULE were implemented in Modula-2 source code.

IMPLEMENTATION MODULE Utils;

(*	Utillity functions for the MHC Modula-2 compiler.
	This work is free to use for everyone.
	
	Copyright 2010 Jan Verhoeven.
	*)


PROCEDURE CardToHex (c : LONGCARD; VAR str : Identifier; l : CARDINAL);

VAR	i	: CARDINAL;
	digits	: Identifier;

BEGIN
  digits := "0123456789ABCDEF"; 
  i := 0;
  WHILE i < l DO
    str [i] := "0";		(* Initialize destination string	*)
    INC (i)
  END;
  i := l - 1;
  WHILE  c # 0  DO
    str [i] := digits [c MOD 16];
    c := c DIV 16;
    IF  i > 0  THEN  DEC (i)  ELSE  RETURN  END
  END;
END CardToHex;

END Utils.
   
Below, each function is explained in more detail.


CardToHex

PROCEDURE CardToHex (c : LONGCARD; VAR str : Identifier; l : CARDINAL);

VAR	i	: CARDINAL;
	digits	: Identifier;

BEGIN
  digits := "0123456789ABCDEF"; 
  i := 0;
  WHILE i < l DO
    str [i] := "0";		(* Initialize destination string	*)
    INC (i)
  END;
  i := l - 1;
  WHILE  c # 0  DO
    str [i] := digits [c MOD 16];
    c := c DIV 16;
    IF  i > 0  THEN  DEC (i)  ELSE  RETURN  END
  END;
END CardToHex;
   
Calling parameters: Next, some variables are defined. Although the 'digits' variable is more of a constant string. And the the procedure begins:
  1. the digits string is filled with all the hexadecimal digits
  2. the loop counter is primed to zero
  3. a WHILE loop is set up to fill the result string with zero's
  4. the loop counter gets it's new value (last token of the string)
  5. a WHILE loop is set up to
  6. and that's it; a seperate RETURN is not required

Page created on 15 July 2010 and

Page equipped with FroogleBuster technology