What are unaligned typecasts in Pascal expressions?
In the Pascal programming language, typecasting enables us to assign values to variables and expressions that are not compatible with the variable's original data type, virtually overriding Pascal's strong typing capabilities.
An unaligned typecast is a special type of typecast. Actually, this is not a true typecast but in such a scenario, the compiler is informed that the expression may be misaligned, or in other words, it's not on an aligned memory address.
By typecasting an expression with the unaligned keyword, the compiler is instructed to access the data byte by byte.
Let's take a deeper look at the following example to improve our understanding of this topic.
Code example
The following example shows how to fetch an unaligned variable:
program hello;Varv_array : packed Array[1..10] of Byte;v : LongInt;beginwriteln('Start...');For v:=1 to 10 dov_array[v]:=v;writeln('v = ', (PInteger(Unaligned(@v_array[3]))^));writeLn('The Binary representation of the byte in string format = ' , binStr(v_array[3], 8));writeln('End...');end.
Code explanation
Line 1: We refer to the program header. It is used for backward compatibility and is ignored by the compiler.
Line 4: We declare a packed array called
v_arrayof 10 bytes.Line 5: We declare a
LongIntvariablev.Lines 8–9: We iterate across a sequence ranging from
1to10and fill out the arrayv_arraywith the sequence number.Line 11: Using the
@operator, we get the address of the third element of the arrayv_array. WithPInteger, we convert the typed pointer returned by the@operator to an integer type and print out the result.Line 13: Using the function
binStr, we extract and print out astringthat shows the binary representation of the third element of the arrayv_array.
Free Resources