字节序

小心,不要做字节序的假设。尽管PC是按照先低字节(little-endian,小头)的方式存储多字节数值的,但某些高端平台是以另一种方式(big-endian,大头)工作的。只要可能,就应该将代码编写成不依赖于所操作数据的字节序的方式。

Linux内核定义了一组宏,它可以在处理器字节序和特殊字节序之间进行转换。

例如,下面的宏可以将值和对应位的无符号的小头数值互转:

#if __BYTE_ORDER == __LITTLE_ENDIAN
#define cpu_to_le16(x) (x)
#define le16_to_cpu(x) (x)
#define cpu_to_le32(x) (x)
#define le32_to_cpu(x) (x)
#define cpu_to_le64(x) (x)
#define le64_to_cpu(x) (x)
#else
#define cpu_to_le16(x) bswap_16(x)
#define le16_to_cpu(x) bswap_16(x)
#define cpu_to_le32(x) bswap_32(x)
#define le32_to_cpu(x) bswap_32(x)
#define cpu_to_le64(x) bswap_64(x)
#define le64_to_cpu(x) bswap_64(x)
#endif

下面是大头数据的宏:

#if __BYTE_ORDER == __LITTLE_ENDIAN

#define be16_to_cpu(x) bswap_16(x)
#define cpu_to_be16(x) bswap_16(x)
#define be32_to_cpu(x) bswap_32(x)
#define cpu_to_be32(x) bswap_32(x)
#define be64_to_cpu(x) bswap_64(x)
#define cpu_to_be64(x) bswap_64(x)

#elif __BYTE_ORDER == __BIG_ENDIAN

#define be16_to_cpu(x) (x)
#define cpu_to_be16(x) (x)
#define be32_to_cpu(x) (x)
#define cpu_to_be32(x) (x)
#define be64_to_cpu(x) (x)
#define cpu_to_be64(x) (x)

#else

#error "Unknown byte order!"

#endif

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值