Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

Endian swap for numeric types

Title: Endian swap for numeric types Question: Convert WORD and DWORD sized variables to/from little-endian and big-endian format numbers. Useful when loading files using big-endian numeric format. Answer: If you need to load and manipulate files created on non-intel based applications, chances are that the numeric types are stored in big-endian format. This procedure basically reverses the byte ordering of numbers stored in big-endian format to the intel native little-endian format. Big/Little endian format applies to floating point and integer types that are 2 or 4 bytes in length. I use it for loading LightWave3D objects. LightWave was originally written for legacy Amiga computers which were motorola 68000 based. I hope you find it useful. (******************* EndianSwap ************************* Purpose: Reverses byte ordering for numeric types "Big-Endian" "Little-Endian" conversion Input: ValueIn: Pointer The address a WORD or DWORD sized numeric variable on which to perform the byte swap. Size: integer; The length in bytes of the numeric type. Note: Requires a 486+ for execution of BSWAP ******************* EndianSwap *************************) procedure EndianSwap(ValueIn: Pointer; Size: integer); var l: LongWord; w: Word; begin case Size of 2: begin { ValueIn is WORD-sized } w := PWord(ValueIn)^; asm mov ax,w; { move w into ax register } xchg al,ah; { swap lo and hi byte of word } mov w,ax; { move "swapped" ax back to w } end; PWord(ValueIn)^ := w; end; 4: begin { ValueIn is DWORD-sized } l := PLongWord(ValueIn)^; asm mov eax,l; { move l into eax register } BSWAP eax; { reverse the order of bytes in eax } mov l,eax; { move "swapped" eax back to 1 } end; PLongWord(ValueIn)^ := l; end; end; end;