Intel® IXP400 Software

Endianness in Intel® IXP400 Software

We always assume that the byte order value will be set to either Big-Endian or Little-Endian in a define value.

27.3.2Best Practices in Coding of Endian-Independence

Avoid

Code that assumes the ordering of data types in memory.

Casting between different-sized types.

Do

Perform any endian-sensitive data accesses in macros. If the machine is Big-Endian, the macros will not have a performance hit. A Little-Endian machine will interpret the data correctly.

27.3.3Macro Examples: Endian Conversion

A common solution to the endianness conversion problem associated with networking is to define a set of four preprocessor macros: htons(), htonl(), ntohs(), and ntohl(). These macros make the following conversions:

htons(): The macro name can be read “host to network short.”

reorder the bytes of a 16-bit value from processor order to network order.

htonl(): The macro name can be read “host to network long.”

reorder the bytes of a 32-bit value from processor order to network order.

ntohs(): The macro name can be read “network to host short.”

reorder the bytes of a 16-bit value from network order to processor order.

ntohl(): The macro name can be read “network to host long.”

reorder the bytes of a 32-bit value from network order to processor order.

27.3.3.1Macro Source Code

If the processor on which the TCP/IP stack is to be run is itself also Big-Endian, each of the four macros will be defined to do nothing and there will be no run-time performance impact. If the processor is Little-Endian, the macros will reorder the bytes appropriately. These macros would be used when building and parsing network packets and when socket connections are created.

By using macros to handle any possibly sensitive data conversions, the problem of dealing with network byte order (Big-Endian) on a Little-Endian machine will be eliminated. Ideally all network processors would have the same endianness. Because that is not true, understand and use the following macros as needed.

27.3.3.1.1Endianness Format Conversions

#if defined(BIG_ENDIAN) /* the value of A will not be manipulated */ #define htons(A) (A)

Programmer’s Guide

IXP400 Software Version 2.0

April 2005

 

Document Number: 252539, Revision: 007

345

Page 345
Image 345
Intel IXP400 Best Practices in Coding of Endian-Independence, Macro Examples Endian Conversion, Macro Source Code, Avoid