DOES大端机器上htonl()改变字节顺序? [英] DOES htonl() change byte order on BIG ENDIAN machine?

查看:341
本文介绍了DOES大端机器上htonl()改变字节顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从字面上看困惑htonl()。在这么多的链接我发现,code做htonl是:

Literally confused about htonl(). In so many links I found that code to do htonl is :

#define HTONL(n) (((((unsigned long)(n) & 0xFF)) << 24) | \
                  ((((unsigned long)(n) & 0xFF00)) << 8) | \
                  ((((unsigned long)(n) & 0xFF0000)) >> 8) | \
                  ((((unsigned long)(n) & 0xFF000000)) >> 24))

如果在同一code是两个机器跑,它要交换字节顺序。
例如:一个uint32_t的=为0x1;

If the same code is ran on both the machines, it is going to swap the byte orders. Example : uint32_t a = 0x1;

在小尾:

100   1
101   0
102   0
103   0

htonl后(一)

100   0
101   0
102   0
103   1

============================================
   在大端机:

100   0
101   0
102   0
103   1

htonl后(一)

100   1
101   0
102   0
103   0

这是否意味着htonl()将改变字节的顺序,不论机器架构的?

Does that mean that htonl() will change the order of the bytes irrespective of machine architecture ?

推荐答案

如果你正确地使用它,然后它不应该在大端机交换字节。

If you use it correctly then it should not swap bytes on big endian machines.

htonl 是在标题是体系结构相关的定义。通常机/ endian.h 将包括你的架构特定的头部。如果你重新定义它,然后它会做什么,你把它设置为。如果你想真正的行为,那么你应该总是使用正确的架构头。在大端机器这是一个无操作。在小端的机器它往往与特定的处理器指令。

htonl is defined in a header which is architecture specific. Normally machine/endian.h will include your architecture specific header. If you redefine it then it will do what you set it to. If you want the real behaviour then you should always use the right architecture header. On big endian machines it's a no op. On little endian machines it's often linked to a specific processor instruction.

这篇关于DOES大端机器上htonl()改变字节顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆