Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2020-08

Strange swap function, what does it do?

2 messages · 2 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Bo Berglund

I am working on the conversion of a service application from Windows/Delphi to Linux/FPC.

When going through the code I found this procedure, which I do not quite understand the workings of, can someone please explain how it operates?

procedure Swap2(var Source);
var
  H, L: word;
begin
  H := Hi(word(Source));
  L := Lo(word(Source));
  word(Source) := (L * 256) + H;
end;

It is used in the code like this where Hd is a record and numSteps is a word sized field:

Swap2(Hd.numSteps);

In other places when word sized variables need to be swapped (Little/Big-endian conversions) it is done like this instead where CmdProgNum is a smallint value and the built-in swap function is used:

FR.CmdProgNum := Swap(FR.CmdProgNum);

So the code uses a mix of these and I do not understand what the strange looking function does...

Bo Berglund Developer in Sweden

Reply by email

Sven Barth
to Bo Berglund
Bo Berglund wrote 29 lines
I am working on the conversion of a service application from Windows/Delphi to Linux/FPC. When going through the code I found this procedure, which I do not quite understand the workings of, can someone please explain how it operates? procedure Swap2(var Source); var H, L: word; begin H := Hi(word(Source)); L := Lo(word(Source)); word(Source) := (L * 256) + H; end; It is used in the code like this where Hd is a record and numSteps is a word sized field: Swap2(Hd.numSteps); In other places when word sized variables need to be swapped (Little/Big-endian conversions) it is done like this instead where CmdProgNum is a smallint value and the built-in swap function is used: FR.CmdProgNum := Swap(FR.CmdProgNum); So the code uses a mix of these and I do not understand what the strange looking function does...

It also does an endian swap, but in place (it's a *procedure* with a var parameter) instead of as a function that returns the swapped value, but leaves the input untouched.

Regards,
Sven

Reply by email