Endian

From Overbyte
Revision as of 10:58, 25 February 2006 by Sysop (talk | contribs) (→‎Sending numbers over a stream)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Little Endian

A number showed in Little Endian format means that the low order byte is stored at the lowest address in memory, and the high order byte at the highest address. This format is by design used by Intel CPU.

Example

The word value 33000 (decimal), 80E8 (hex) is stored:

Base address + 0 = E8
Base address + 1 = 80

If we transmit it over a stream:

First byte  = E8
Second byte = 80

Big Endian

A number showed in Big Endian format means that the high order byte is stored at the lowest address in memory, and the low order byte at the highest address. This format is by design used by Motorola CPU.

Example

The word value 33000 (decimal), 80E8 (hex) is stored:

Base address + 0 = 80
Base address + 1 = E8

If we transmit it over a stream:

First byte  = 80
Second byte = E8

Sending numbers over a stream

It is common habitude to send numbers in Big Endian over a stream. This because it is better human read. In the socket terminologuy it is designated as "network byte order".

Winsock provides functions to convert back and forth between host processor byte order (When run on an Intel processor, it is Little Endian) and network byte order (Big Endian). ICS make those functions availables in the wsocket.pas unit:

  • WSocket_htons Host to network short (16 bit integer)
  • WSocket_htonl Host to network long (32 bit integer)

When those functions are used, the source code is compatible with any processor architecture. Not very useful actualy since Delphi generate code for Intel architecture only !

History

The terms big endian and little endian are derived from the Lilliputians of Gulliver's Travels, whose major political issue was whether soft boiled eggs should be opened on the big side or the little side.

Conversion code

Delphi has no function provided to change the endian of an integer, but this one will do:

function ChangeEndian(Number: integer): integer;
asm
    bswap eax
end;

If you want to use a class method then the first argument is a pointer to Self, so you must use this code:

function TMyClass.ChangeEndian(Number: integer): integer;
asm
    mov   eax, edx
    bswap eax
end;