The swap function

Description

The swap function returns an integer value that is calculated by reversing the order of the bytes in the parameter passed to it. In other words this function converts little endian integer values to big endian integer values and vice-versa.

Parameter

The swap function's only parameter is an expression of one of the following types:

Notes

The swap function is designed to swap four byte (i.e. 32-bit) integral values. If you pass two byte (i.e. 16-bit), or one byte (i.e. 8-bit) integral values, they are converted to four byte integral values before the swap is performed. As a result of this conversion the result of the swap might not be what you would expect. See the examples below for more information.

Example

For example, assuming 32 bit little endian integers then 256 is stored in four bytes as follows:

   0 0 1 0

So swap(256) results in the following integer:

   0 1 0 0

which is equal to 65536.

As mentioned in the  Notes above swapping two byte or one byte values might not give you the results you expect. So what do you do if you have two byte values that you want to swap, well consider the following program:

program example(output);
var
 x : shortint;
begin
 x:=$1234;
 x:=swap(x);
 writeln(hex(x));
end.

This program does not produce the output that you might expect (i.e. 3412). This is because the swap function will convert its parameter into an four byte integer (producing the following bytes $00 $00 $12 $34), and then swap around these bytes (producing $34 $12 $00 $00). Actually a run-time error (vaue out of range) will be issued because the value returned by the swap function (i.e. $34120000) is too large to fit in a variable of type shortint. As you can see the value you probably want is stored in the upper 16-bits of the result while the lower 16-bits contain zero. The solution to this problem is to shift the value in the upper 16-bits into the lower 16-bits, before the assignment into the shortint variable. You can do this by changing the

 x:=swap(x); 

into either

 x:= swap(x) shr 16; 

or

 x:=swap(x) div $10000; 

Portability

Operating Systems: All
Standard Pascal: No