Inside the computer data storage are usually two:
- Big endian: high byte first. (High there is a low address)
- Little-endian mode: the low byte first. (There is a low address low)
32-bit data width 0x12345678 an example, the big endian mode and a method of storing a little-endian mode the following table:
Memory address | 0x8000 | 0x8001 | 0x8002 | 0x8003 |
---|---|---|---|---|
Big-endian mode | 0x12 | 0x34 | 0x 56 | 0x78 |
Little-endian mode | 0x78 | 0x56 | 0x34 | 0x12 |
Byte order conversion function
Linux provides htonl, htons, ntohl ntohs and four big endian mode and a function for processing data exchanged little endian mode.
#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);
When the function call returns successfully values obtained after processing, it returns -1 if the call fails.
- htonl function: The 32-bit PC, the data (stored little endian mode) is converted into 32-bit data transfer network (big-endian mode storage).
- htons function: The 16-bit PC, the data (stored little endian mode) is converted into 16-bit data transfer network (big-endian mode storage).
- ntohl functions: converting 32-bit data transmission network 32 to a PC data.
- ntohs functions: converting 16-bit data transmission network 16 to a PC data.
The above parameters are a function of a value corresponding to the required conversion, h for host, on behalf of n network, S representative of short, on behalf of the I long; long 32-bit data is often used to store an IP address, and the 16-bit data is typically used for short storage port number.