Turning Integers and words

This article was originally posted to delphi3000.com

Sometimes it is nessescary to turn the bytes of an integer. This is known as the big-endian/little-endian problem, and occurs when you receive data from a machine with another byte order:



Some machines arranges bytes from left to right.

Other arranges them from right to left.



Delphi has implemented a function called swap() that can turn integers. But here are some examples on how to do it yourself.



// Turning a smallint (16 bit signed)

function i16( i : smallint ) : smallint;

var

  x1 : smallint;

  x2 : array[0..1] of byte absolute x1;

  x3 : array[0..1] of byte absolute i;

begin

  x2[0] := x3[1];

  x2[1] := x3[0];

  result := x1;

end;



// Turning a word (16 bit unsigned)

function r16( i : word) : word;



var

  x1 : word;

  x2 : array[0..1] of byte absolute x1;

  x3 : array[0..1] of byte absolute i;

begin

  x2[0] := x3[1];

  x2[1] := x3[0];

  result := x1;

end;



// Turning a longint (32 bit signed)

function r32( i : longint) : longint;

var

   x1 : longint;

   x2 : array[1..4] of byte absolute x1;

   x3 : array[1..4] of byte absolute i;

begin

   x2[1] := x3[4];

   x2[2] := x3[3];

   x2[3] := x3[2];

   x2[4] := x3[1];

   result := x1;

end;



Do you see the pattern?

 

Share this article!

Follow us!

Find more helpful articles: