版本

这些功能已在2.9版中添加到glibc。

遵循规范

这些功能是非标准的。在BSD上存在类似的功能,其中所需的头文件是。不幸的是,NetBSD,FreeBSD和glibc并未遵循这些函数的原始OpenBSD命名约定,因此nn组件始终出现在函数名的末尾(因此,例如,在NetBSD,FreeBSD和glibc中,等效项OpenBSD的" betoh32"是" be32toh")。

备注

这些功能类似于较旧的byteorder(3)系列功能。例如,be32toh()与ntohl()相同。

byteorder(3)函数的优点是它们是所有UNIX系统上可用的标准函数。另一方面,它们是为在TCP / IP上下文中使用而设计的,这意味着它们缺少本页中所述的64位和little-endian变体。

另外参见

bswap(3),字节序(3)

出版信息

这个页面是Linux手册页项目5.08版的一部分。有关项目的说明、有关报告错误的信息以及此页面的最新版本,请访问https://www.kernel.org/doc/man-pages/

示例

下面的程序显示将整数从主机字节顺序转换为小字节序和大字节序的结果。由于主机字节顺序是小端或大端,因此这些转换中只有一个会起作用。当我们在诸如x86-32的小端系统上运行该程序时,我们看到以下内容:

$ ./a.out
x.u32 = 0x44332211
htole32(x.u32) = 0x44332211
htobe32(x.u32) = 0x11223344

Program source

#include <endian.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
    union {
        uint32_t u32;
        uint8_t arr[4];
    } x;

    x.arr[0] = 0x11;    /* Lowest-address byte */
    x.arr[1] = 0x22;
    x.arr[2] = 0x33;
    x.arr[3] = 0x44;    /* Highest-address byte */

    printf("x.u32 = 0x%x\n", x.u32);
    printf("htole32(x.u32) = 0x%x\n", htole32(x.u32));
    printf("htobe32(x.u32) = 0x%x\n", htobe32(x.u32));

    exit(EXIT_SUCCESS);
}

名称

htobe16,htole16,be16toh,le16toh,htobe32,htole32,be32toh,le32toh,htobe64,htole64,be64toh,le64toh-在主机和大/小尾数字节顺序之间转换值

语法

#include <endian.h>

uint16_t htobe16(uint16_t host_16bits);
uint16_t htole16(uint16_t host_16bits);
uint16_t be16toh(uint16_t big_endian_16bits);
uint16_t le16toh(uint16_t little_endian_16bits);

uint32_t htobe32(uint32_t host_32bits);
uint32_t htole32(uint32_t host_32bits);
uint32_t be32toh(uint32_t big_endian_32bits);
uint32_t le32toh(uint32_t little_endian_32bits);

uint64_t htobe64(uint64_t host_64bits);
uint64_t htole64(uint64_t host_64bits);
uint64_t be64toh(uint64_t big_endian_64bits);
uint64_t le64toh(uint64_t little_endian_64bits);

glibc的功能测试宏要求(请参阅feature_test_macros(7)):

htobe16(),htole16(),be16toh(),le16toh(),htobe32(),htole32(),be32toh(),le32toh(),htobe64(),htole64(),be64toh(),le64toh():

Since glibc 2.19:
        _DEFAULT_SOURCE
    In glibc up to and including 2.19:
        _BSD_SOURCE
ENDIAN - Linux手册页

Linux程序员手册 第3部分
更新日期: 2020-06-09

说明

这些函数将整数值的字节编码从当前CPU("主机")使用的字节顺序转换为little-endian和big-endian字节顺序。

每个函数名称中的数字nn表示该函数处理的整数的大小,可以是16位,32位或64位。

名称格式为" htobe nn"的函数将从主机字节顺序转换为大端顺序。

名称格式为" htole nn"的函数将从主机字节顺序转换为小端顺序。

名称形式为" be nn toh"的函数将从big-endian顺序转换为主机字节顺序。

名称形式为" le nn toh"的函数会从little-endian顺序转换为主机字节顺序。

日期:2019-08-20 17:59:55 来源:oir作者:oir