NAME
be16toh be32toh
be64toh htobe16
htobe32 htobe64
htole16 htole32
htole64 le16toh
le32toh le64toh —
convert values between host and specified byte
order
SYNOPSIS
#include
<endian.h>
uint16_t be16toh(uint16_t big_endian_16bits); uint32_t be32toh(uint32_t big_endian_32bits); uint64_t be64toh(uint64_t big_endian_64bits); uint16_t htobe16(uint16_t host_16bits); uint32_t htobe32(uint32_t host_32bits); uint64_t htobe64(uint64_t host_64bits); uint16_t htole16(uint16_t host_16bits); uint32_t htole32(uint32_t host_32bits); uint64_t htole64(uint64_t host_64bits); uint16_t le16toh(uint16_t little_endian_16bits); uint32_t le32toh(uint32_t little_endian_32bits); uint64_t le64toh(uint64_t little_endian_64bits);
DESCRIPTION
These functions shall convert integer values of various sizes between host representations and representations in a specified order.
On some implementations, these functions are defined as macros.
A little-endian representation of an integer has the least significant byte stored as the first byte, with the significance of the bytes increasing as the byte address increases. A big-endian representation has the most significant byte as the first byte, with the significance of the bytes reducing as the byte address increases.
- Note:
- Network byte order is big-endian.
For example, the uint32_t value 0x01020304 is represented as the four bytes 0x04, 0x03, 0x02, 0x01 on a little-endian host, and as 0x01, 0x02, 0x03, 0x04 on a big-endian host.
For each of the sizes 16, 32 and 64, the htobeSIZE () function shall convert from whatever order the host uses to big-endian representation, htoleSIZE () shall convert to little-endian representation, beSIZEtoh () shall convert from big-endian to host order, and leSIZEtoh () shall convert from little-endian to host order.
RETURN VALUE
These functions shall return an unsigned integer of the appropriate size and representation.
ERRORS
No errors are defined.
EXAMPLES
#include <endian.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
uint32_t val;
if (argc > 1) {
val = (uint32_t)strtoul(argv[1], NULL, 0);
printf("Value: %08x\n", val);
printf("As bytes:\n");
union {
uint32_t asint;
unsigned char asbytes[sizeof(uint32_t)];
} u;
printf("Little endian: ");
u.asint = htole32(val);
for (int i = 0; i < sizeof(uint32_t); i++) {
printf("%02x ", u.asbytes[i]);
}
printf("\n");
printf("Big endian : ");
u.asint = htobe32(val);
for (int i = 0; i < sizeof(uint32_t); i++) {
printf("%02x ", u.asbytes[i]);
}
printf("\n");
}
return 0;
}
APPLICATION USAGE
Since network order is defined as big-endian, the following functions are equivalent if <arpa/inet.h> is included:
| <endian.h> | <arpa/inet.h> |
| htobe32 | htonl |
| htobe16 | htons |
| be32toh | ntohl |
| be16toh | ntohs |
RATIONALE
None.
FUTURE DIRECTIONS
None.
SEE ALSO
XBD <arpa/inet.h>, <endian.h>
CHANGE HISTORY
First released in Issue 8.