New language extension: BYTE data type
Posted: Fri Jul 27, 2012 1:30 pm
Starting with release 4.4 of Astrobe the data type BYTE is included as an Oberon language extension to replace the existing extension SYSTEM.BYTE. The BYTE type is primarily intended to be used when transferring 8- and 16-bit data to and from peripheral devices. Although BYTE variables could be used wherever an INTEGER variable is allowed (except where noted here) INTEGERs should always be used unless there is a compelling reason to do otherwise.
BYTE is an unsigned INTEGER with a minimum value of 0 and a maximum value of 255. No overflow checking is performed on BYTE variables at runtime.
BYTE variables can be assigned to INTEGER variables. Constants in the range 0..255 can be assigned to BYTE variables. Attempts to assign a constant outside this range will result in the compile-time error: incompatible assignment.
An example of a safe way of typecasting an INTEGER value to a BYTE is as follows:
If a formal parameter to a procedure is defined as ARRAY OF BYTE the actual parameter may be of any data type. The parameter can then be accessed byte-by-byte in the body of the procedure e.g.
If a parameter is truly an array of bytes with a fixed size, it should be defined as a TYPE to prevent arbitrary data types from being passed to it e.g.
BYTE is an unsigned INTEGER with a minimum value of 0 and a maximum value of 255. No overflow checking is performed on BYTE variables at runtime.
BYTE variables can be assigned to INTEGER variables. Constants in the range 0..255 can be assigned to BYTE variables. Attempts to assign a constant outside this range will result in the compile-time error: incompatible assignment.
An example of a safe way of typecasting an INTEGER value to a BYTE is as follows:
Code: Select all
PROCEDURE* IntToByte(i: INTEGER): BYTE;
BEGIN
ASSERT(LSR(i, 8) = 0);
RETURN SYSTEM.VAL(BYTE, i)
END IntToByte;
If a formal parameter to a procedure is defined as ARRAY OF BYTE the actual parameter may be of any data type. The parameter can then be accessed byte-by-byte in the body of the procedure e.g.
Code: Select all
VAR
data: INTEGER;
b1, b2, b3, b4: BYTE;
PROCEDURE WordToBytes(w: ARRAY OF BYTE; VAR b1, b2, b3, b4: BYTE);
BEGIN
ASSERT(LEN(w) = 4, 20);
b1 := w[0];
b2 := w[1];
...
...
WordToBytes(data, b1, b2, b3, b4);
Code: Select all
TYPE
Buffer = ARRAY 256 OF BYTE;
PROCEDURE SendData(bytes: Buffer);