bdn.borland.com

Article #28964: Converting Double Types from Little Endian to Big Endian Using Variant Records.

Question: How can I convert my doubles from Little Endian to Big Endian?

Solution: The conversion is very simple. It requires that you swap the 8 underlying bytes of the double such that the first byte goes to the last, the second byte goes to the second of last, and so on. The following Record definition and procedure should convert you doubles from Little Endian to Big Endian and back again.

type
//enumeration used in variant record
BytePos = (EndVal, ByteVal);
PEndianCnvRec = ^EndianCnvRec;
EndianCnvRec = packed record
case pos: BytePos of
//The value we are trying to convert
EndVal: (EndianVal: double);
//Overlapping bytes of the double
ByteVal: (Bytes: array[0..SizeOf(Double)-1] of byte);
end;
//A gets B's values swapped
procedure SwapBytes( A, B: PEndianCnvRec );
var
i: integer;
begin
for i := high(A.Bytes) downto low(A.Bytes) do
A.Bytes[i] := B.Bytes[High(A.Bytes) — i];
end;
Below is an example of how one might use the above procedure. Start a New application and drop a button on the form. Then use the following code for the button click:

procedure TForm1.Button1Click(Sender: TObject);
var
a,b,c: EndianCnvRec;
begin
a.EndianVal := 23344.55555;
SwapBytes(@b,@a);
ShowMessage(FloatToStr(b.EndianVal));
SwapBytes(@c,@b);
ShowMessage(FloatToStr(c.EndianVal));
end;

Last Modified: 15-AUG-02