ZetCode

Modula-2 type conversions

last modified November 27, 2026 Modula-2

Modula-2 never converts a value to another type behind the programmer's back. An integer is not added to a real, and a character is not used as a number, until the program says so with a standard function. This article covers those functions: ORD and CHR for characters, CAP, FLOAT and TRUNC for reals, the general VAL, and type transfers, which reinterpret the bits of a value instead of converting it.

Characters and codes

ORD returns the code of a character as a CARDINAL, and CHR turns a code back into a character. Because the digits and the letters have consecutive codes, the distance from '0' or 'A' gives a digit's value or a letter's position.

codes.mod
MODULE codes;

FROM InOut IMPORT WriteString, WriteLn, WriteCard, Write;

VAR
  digit: CHAR;
  value: CARDINAL;

BEGIN
  digit := '7';
  WriteString("ORD('7'):          ");
  WriteCard(ORD(digit), 0);
  WriteLn;

  value := ORD(digit) - ORD('0');
  WriteString("Digit value:       ");
  WriteCard(value * 6, 0);
  WriteString(" (7 * 6)");
  WriteLn;

  value := 4;
  WriteString("Digit for 4:       ");
  Write(CHR(ORD('0') + value));
  WriteLn;
  WriteString("Letter number 3:   ");
  Write(CHR(ORD('A') + 3 - 1));
  WriteLn
END codes.

ORD(digit) - ORD('0') converts the character '7' into the number 7, which can then be multiplied. CHR(ORD('0') + value) goes the other way and turns 4 into the character '4'.

$ gm2 codes.mod -o codes
$ ./codes
ORD('7'):          55
Digit value:       42 (7 * 6)
Digit for 4:       4
Letter number 3:   C

Upper case with CAP

CAP returns the upper-case form of a letter. Other characters are returned unchanged. There is no standard function for lower case.

capitals.mod
MODULE capitals;

FROM InOut IMPORT WriteString, WriteLn, Write;

VAR
  answer, sign: CHAR;

BEGIN
  answer := 'y';
  sign := '%';
  WriteString("CAP('y'): "); Write(CAP(answer)); WriteLn;
  WriteString("CAP('Y'): "); Write(CAP('Y')); WriteLn;
  WriteString("CAP('%'): "); Write(CAP(sign)); WriteLn;
  WriteString("Lower case of 'Q': ");
  Write(CHR(ORD('Q') - ORD('A') + ORD('a')));
  WriteLn
END capitals.

The lower-case letter is computed from the codes: the distance of 'Q' from 'A' is added to the code of 'a'. This works because both alphabets have consecutive codes in ASCII.

$ gm2 capitals.mod -o capitals
$ ./capitals
CAP('y'): Y
CAP('Y'): Y
CAP('%'): %
Lower case of 'Q': q

Whole numbers to reals

FLOAT converts a whole number into a REAL. It is needed whenever integers take part in a real computation, such as an average.

floats.mod
MODULE floats;

FROM InOut IMPORT WriteString, WriteLn, WriteInt;
FROM RealInOut IMPORT WriteReal;

VAR
  points, games: CARDINAL;
  goals: INTEGER;
  average, change: REAL;

BEGIN
  points := 47;
  games := 12;
  WriteString("Integer average: ");
  WriteInt(points DIV games, 0);
  WriteLn;

  average := FLOAT(points) / FLOAT(games);
  WriteString("Real average: ");
  WriteReal(average, 0);
  WriteLn;

  goals := -9;
  change := FLOAT(goals) / 2.0;
  WriteString("Change per half: ");
  WriteReal(change, 0);
  WriteLn
END floats.

points DIV games drops the fraction. Converting both operands with FLOAT gives the exact average. In PIM, FLOAT takes a CARDINAL; GNU Modula-2 accepts an INTEGER as well, as in the last computation. LFLOAT converts to LONGREAL.

$ gm2 floats.mod -o floats
$ ./floats
Integer average: 3
Real average: 3.916667
Change per half: -4.500000

Reals to whole numbers

TRUNC converts a real into a whole number by dropping the fraction. The PIM library has no rounding function, so a value is rounded by adding or subtracting one half before truncating.

truncation.mod
MODULE truncation;

FROM InOut IMPORT WriteString, WriteLn, WriteInt, WriteCard;

VAR
  price, loss: REAL;
  whole: CARDINAL;
  signed: INTEGER;

BEGIN
  price := 18.75;
  whole := TRUNC(price);
  WriteString("TRUNC(18.75):       ");
  WriteCard(whole, 0);
  WriteLn;

  whole := TRUNC(price + 0.5);
  WriteString("Rounded 18.75:      ");
  WriteCard(whole, 0);
  WriteLn;

  loss := -3.7;
  signed := TRUNC(loss);
  WriteString("TRUNC(-3.7):        ");
  WriteInt(signed, 0);
  WriteLn;

  signed := TRUNC(loss - 0.5);
  WriteString("Rounded -3.7:       ");
  WriteInt(signed, 0);
  WriteLn
END truncation.

TRUNC cuts towards zero, so TRUNC(-3.7) is -3, not -4. For negative numbers the half is subtracted instead of added. GNU Modula-2 rejects ROUND in the default PIM mode with "procedure function ‘ROUND’ is undefined".

$ gm2 truncation.mod -o truncation
$ ./truncation
TRUNC(18.75):       18
Rounded 18.75:      19
TRUNC(-3.7):        -3
Rounded -3.7:       -4

The VAL function

VAL(T, x) converts the value x to the type T. It was added in the third edition of PIM and covers the conversions of the previous sections in one form.

values.mod
MODULE values;

FROM InOut IMPORT WriteString, WriteLn, WriteInt, WriteCard, Write;
FROM RealInOut IMPORT WriteReal, WriteLongReal;

VAR
  i: INTEGER;
  c: CARDINAL;
  r: REAL;
  lr: LONGREAL;
  ch: CHAR;

BEGIN
  i := 42;
  c := VAL(CARDINAL, i);
  WriteString("VAL(CARDINAL, 42):    "); WriteCard(c, 0); WriteLn;

  ch := VAL(CHAR, 77);
  WriteString("VAL(CHAR, 77):        "); Write(ch); WriteLn;

  r := VAL(REAL, i);
  WriteString("VAL(REAL, 42):        "); WriteReal(r, 0); WriteLn;

  r := 9.99;
  i := VAL(INTEGER, r);
  WriteString("VAL(INTEGER, 9.99):   "); WriteInt(i, 0); WriteLn;

  lr := VAL(LONGREAL, r);
  WriteString("VAL(LONGREAL, 9.99):  "); WriteLongReal(lr, 0); WriteLn
END values.

VAL(CHAR, 77) does the job of CHR, VAL(REAL, i) that of FLOAT, and VAL(INTEGER, r) that of TRUNC. The type always comes first, which makes the target of the conversion visible at the call.

$ gm2 values.mod -o values
$ ./values
VAL(CARDINAL, 42):    42
VAL(CHAR, 77):        M
VAL(REAL, 42):        42.000000
VAL(INTEGER, 9.99):   9
VAL(LONGREAL, 9.99):  9.990000

Integers and cardinals

The operators article showed that an INTEGER and a CARDINAL cannot appear in the same expression. One operand is converted with VAL. Assignment is more lenient: the two types are assignment compatible.

mixed.mod
MODULE mixed;

FROM InOut IMPORT WriteString, WriteLn, WriteInt, WriteCard;

VAR
  balance: INTEGER;
  deposit, stock: CARDINAL;

BEGIN
  balance := -40;
  deposit := 100;
  WriteString("New balance: ");
  WriteInt(balance + VAL(INTEGER, deposit), 0);
  WriteLn;

  balance := deposit;
  WriteString("Assigned:    ");
  WriteInt(balance, 0);
  WriteLn;

  balance := 250;
  stock := balance;
  WriteString("In stock:    ");
  WriteCard(stock + 10, 0);
  WriteLn
END mixed.

VAL(INTEGER, deposit) turns the cardinal into an integer, so the sum compiles. The two assignments copy a value from one type to the other without any conversion function. This is safe only when the value fits the target type, as the next section shows.

$ gm2 mixed.mod -o mixed
$ ./mixed
New balance: 60
Assigned:    100
In stock:    260

Range checks

A negative integer has no CARDINAL value. By default GNU Modula-2 copies the bits and the value wraps around; with -fsoft-check-all the program checks the assignment at run time.

range.mod
MODULE range;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

VAR
  change: INTEGER;
  stock: CARDINAL;

BEGIN
  change := -3;
  stock := change;
  WriteString("Stock: ");
  WriteCard(stock, 0);
  WriteLn
END range.

Without checks, -3 becomes 4294967293. The checked build stops at the assignment instead. The message names the types the other way round, but it points at line 11, where the integer is assigned to the cardinal. In GNU Modula-2 15.2 the checks do not cover VAL, so VAL(CARDINAL, -3) wraps even in a checked build.

$ gm2 range.mod -o range
$ ./range
Stock: 4294967293
$ gm2 -fsoft-check-all range.mod -o range
$ ./range
range.mod:11:3: In program module range
range.mod:11:3:assignment will cause a range error, as the runtime instance value of ‘CARDINAL’ does not overlap with the type ‘INTEGER’
Aborted (core dumped)

Long integers

VAL also converts between INTEGER and LONGINT. Widening is always safe; narrowing is safe only while the value fits into 32 bits.

longs.mod
MODULE longs;

FROM InOut IMPORT WriteString, WriteLn, WriteInt;
FROM LongIO IMPORT WriteLongInt;

VAR
  population: LONGINT;
  small: INTEGER;

BEGIN
  small := 2000000000;
  population := VAL(LONGINT, small) * 4;
  WriteString("Widened:   ");
  WriteLongInt(population, 0);
  WriteLn;

  small := VAL(INTEGER, population DIV 1000);
  WriteString("Narrowed:  ");
  WriteInt(small, 0);
  WriteLn;

  small := VAL(INTEGER, population);
  WriteString("Too large: ");
  WriteInt(small, 0);
  WriteLn
END longs.

The product is computed in LONGINT, because one operand was widened first; 2000000000 times 4 would not fit into an INTEGER. Dividing by 1000 brings the value back into range. The last conversion keeps only the low 32 bits of 8000000000 and prints a wrong negative number, with or without -fsoft-check-all.

$ gm2 longs.mod -o longs
$ ./longs
Widened:   8000000000
Narrowed:  8000000
Too large: -589934592

Type transfers

A type name used like a function, as in CARDINAL(x), is a type transfer. It does not convert the value; it takes the bits of x and reads them as the other type. VAL converts the value.

transfers.mod
MODULE transfers;

FROM InOut IMPORT WriteString, WriteLn, WriteInt, WriteCard;

VAR
  ratio: SHORTREAL;
  n: INTEGER;
  c: CARDINAL;

BEGIN
  ratio := 1.0;
  WriteString("VAL(CARDINAL, 1.0):   ");
  WriteCard(VAL(CARDINAL, ratio), 0);
  WriteLn;
  WriteString("CARDINAL(1.0):        ");
  WriteCard(CARDINAL(ratio), 0);
  WriteLn;

  n := -1;
  WriteString("CARDINAL(-1):         ");
  WriteCard(CARDINAL(n), 0);
  WriteLn;
  c := MAX(CARDINAL);
  WriteString("INTEGER(4294967295):  ");
  WriteInt(INTEGER(c), 0);
  WriteLn
END transfers.

VAL(CARDINAL, ratio) converts 1.0 into 1. The type transfer CARDINAL(ratio) returns 1065353216, the 32-bit pattern that encodes 1.0 as a SHORTREAL. Between INTEGER and CARDINAL the two forms give the same bits, so -1 reads as the largest cardinal and back. The last transfer reads a variable: GNU Modula-2 rejects INTEGER(MAX(CARDINAL)), because the constant does not fit into an INTEGER. Type transfers belong to low-level code; for ordinary conversions use VAL.

$ gm2 transfers.mod -o transfers
$ ./transfers
VAL(CARDINAL, 1.0):   1
CARDINAL(1.0):        1065353216
CARDINAL(-1):         4294967295
INTEGER(4294967295):  -1

Transfers need equal sizes

A type transfer only works between types of the same size. A CHAR is one byte and an INTEGER four, so one cannot be reinterpreted as the other.

samesize.mod
MODULE samesize;

FROM InOut IMPORT WriteLn, WriteInt;

VAR
  letter: CHAR;
  n: INTEGER;

BEGIN
  letter := 'A';
  n := INTEGER(letter);
  WriteInt(n, 0);
  WriteLn
END samesize.

The compiler calls the type transfer a cast and rejects it. ORD(letter) or VAL(INTEGER, letter) would give the code 65.

$ gm2 samesize.mod -o samesize
samesize.mod:11:23: error: can only CAST objects of the same size
   11 |   n := INTEGER(letter);
      |                       ^

Next steps

The conditionals article chooses between statements with IF and CASE, and the loops article repeats them.

Source

The GNU Modula-2 manual

Modula-2 language reference at modula2.org

In this article we have converted values between types in Modula-2: characters and codes with ORD, CHR and CAP, whole numbers and reals with FLOAT and TRUNC, any pair of types with VAL, and raw bits with type transfers. The data types article lists the types and their ranges, and the operators article shows the expressions that need these conversions.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Modula-2 tutorials.