Niroshan Rajadurai

  • Increase font size
  • Default font size
  • Decrease font size

One Little Endian - Cross platform data handling issues

E-mail Print PDF
User Rating: / 1
PoorBest 

TCP/IP networks are rarely homogenous; they usually consist of a wide variety of machines, architectures, and operating systems - each storing binary data in various forms. The actual storage format is transparent as long as you access data locally (i.e., on the same machine). However, you must consider the data storage format differences when transmitting or receiving data across machines and networks.

Any data larger than a single byte can be store its bytes at least two ways: big endian order and little endian order.

Big endian machines store the most significant byte at the lowest memory address. The remaining bytes occupy higher memory addresses, in ascending order. For example, the 32-bit hexadecimal integer 0x0a0b0c0d has four bytes with the following values: 0a, 0b, 0c, 0d. The first, and most significant, byte, 0a, occupies the lowest memory address. The second byte, 0b, occupies a memory address higher than the first byte's address, and the rest follow in kind. By contrast, little endian architectures use exactly the opposite byte ordering. Thus, under a little endian architecture, the most significant byte, 0a, would occupy the highest memory address.

The TCP/IP protocol mandates big endian byte ordering for transmitting multibyte values. For this reason, a big endian byte order is also called a "network byte order". If the target host uses a little endian order, then it must convert all incoming multibyte values from network order to little endian order. Likewise, before transmitting multibyte values via TCP/IP, such a host must convert them to network byte order. Fortunately, you don't have to reinvent the wheel by writing the conversion code. The <netinet/in.h> header file declares four functions that convert between host byte order and network byte order:

 

  • unsigned int htonl (unsigned int hostlong);
  • unsigned short htons (unsigned short hostshort);
  • unsigned int ntohl (unsigned int netlong);
  • unsigned short ntohs (unsigned short netshort);

 

Note that no signed counterparts for these functions exist. Although they take and return unsigned values, they handle signed values just as well.

Suppose your machine uses little endian order. To transmit the 32-bit value 0x0a0b0c0d over a TCP/IP connection you have to call htonl() and transmit the result:

transmit_num(htonl(0x0a0b0c0d));

Likewise, to convert an incoming 32-bit value, use ntohl():

int n=ntohl(get_number_from_network());

 

Comments (0)
Last Updated on Wednesday, 05 January 2011 16:38  

Related Articles