[fpc-pascal] Delphi-FPC portable code for endian conversion

Bo Berglund bo.berglund at gmail.com
Sat Jun 4 00:39:50 CEST 2016


On Sat, 4 Jun 2016 00:05:21 +0200, Sven Barth
<pascaldragon at googlemail.com> wrote:

>FPC's NToBE and BEToN routines indeed only convert if necessary. I don't
>know about the Delphi's Swap routines, but alone from the name I'd say that
>they swap unconditionally (though considering that Delphi runs only on
>little endian CPUs that provably won't matter).
>
>> I have tried to figure out a set of {$IFDEF } statements but so far
>> with no success.
>
>I'd say that "ifdef fpc" should do the job.
>
Yes, but then I would also need to use the NToBE and BEToN functions
in the FPC code block and my existing code in the D2007 code in order
for it to work when I run on FPC but in Linux on x86...

Meanwhile I realized I could do as follows instead:

interface
  ...
var
  IsLittleEndian: boolean;
implementation
var
  _Tmp: array[0..1] of byte;
  _Tst: word;

  ...

procedure Swap4 (var Source);
{Swap the byte order of a 4-byte variable}
type
  Reverse = packed record
    B1 : Byte;
    I2 : Word;
    B4 : Byte;
  end;
var
  Bsw : Byte;
begin
  Bsw :=  Reverse(Source).B1;
  Reverse(Source).B1 := Reverse(Source).B4;
  Reverse(Source).B4 := Bsw;
  Reverse(Source).I2 := Swap(Reverse(Source).I2);
end;

....

initialization
  _Tmp[0] := 57;
  _Tmp[1] := 48;
  Move(_Tmp[0], _Tst, 2);
  IsLittleEndian := (_Tst = 12345);
end.

Then in each endian conversion function I could do as the following
example:

procedure FileDirRecEndianConv(var FR: TSSFileDirRec);
begin
  if IsLittleEndian then
  begin
    Swap4(FR.FileLen);
    FR.StartBlock := Swap(FR.StartBlock);
    FR.CmdNum := Swap(FR.CmdNum);
    FR.Meascount := Swap(FR.Meascount);
    Swap4(FR.Xloc);
    Swap4(FR.Yloc);
    Swap4(FR.Zloc);
    Swap4(FR.ScaleFactor);
    Swap4(FR.P_X);
    Swap4(FR.P_Y);
    Swap4(FR.P_Z);
    Swap4(FR.InfiniteX);
    Swap4(FR.InfiniteY);
    Swap4(FR.InfiniteZ);
  end;
end;

What this does is that it checks system endian on program startup
(once) and then uses this flag all through to either convert or not.
Still with my own Swap4() procedure and the built in Swap() function.

-- 
Bo Berglund
Developer in Sweden



More information about the fpc-pascal mailing list