C计划中的钻头操作和Endianness
我很难理解我的计算机的确切方式,具体取决于dandianness。 我读过此线程 and 本文在两个来源中描述的几个程序,所有这些程序似乎都输出了我的机器确实很小的Endian)。 我有以下宏定义使用SDL和交换2和4个字节值,以防:
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
#define HTON16(n) (n)
#define NTOH16(n) (n)
#define HTON32(n) (n)
#define NTOH32(n) (n)
#define HTON64(n) (n)
#define NTOH64(n) (n)
#else
#define HTON16(n) SDL_Swap16(n)
#define NTOH16(n) SDL_Swap16(n)
#define HTON32(n) SDL_Swap32(n)
#define NTOH32(n) SDL_Swap32(n)
#define HTON64(n) SDL_Swap64(n)
#define NTOH64(n) SDL_Swap64(n)
#endif
我的问题是: 在将2个字节编号(在这种情况下为43981 = 0xABCD)写到char [],例如在条目0时,以下代码将在Little Endian(即0xcdab)中产生前2个字节的数据做相反的事情:
char data[100];
int host_value = 43981; // 0xabcd
int net_value = HTON16(host_value);
data[0] = (net_value & 0xff00) >> 8;
data[1] = (net_value & 0xff);
我对先前问题的解决方案是不在主机值上使用Hton16,而是用它来操作,就好像我的机器是大的Endian一样。 另外,在同一台计算机中,在执行以下操作以将相同的主机值编写为数据时,它确实会产生数据,以将两个第一个字节设置为0xABCD:
*((unsigned short *)&data[0]) = HTON16(host_value);
我想理解为什么这两种情况的工作方式有所不同。任何帮助都将受到赞赏。
I am having trouble trying to understand how exactly is my computer doing bitwise operations depending on endianness.
I've read this thread and this article and I think I have confirmed my machine works in little endian (I have tried several programs described in both sources and all of them seem to output my machine is indeed little endian).
I have the following macros defined that use SDL and swap 2 and 4 byte values in case needed:
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
#define HTON16(n) (n)
#define NTOH16(n) (n)
#define HTON32(n) (n)
#define NTOH32(n) (n)
#define HTON64(n) (n)
#define NTOH64(n) (n)
#else
#define HTON16(n) SDL_Swap16(n)
#define NTOH16(n) SDL_Swap16(n)
#define HTON32(n) SDL_Swap32(n)
#define NTOH32(n) SDL_Swap32(n)
#define HTON64(n) SDL_Swap64(n)
#define NTOH64(n) SDL_Swap64(n)
#endif
My problem is:
When writing a 2 byte number (in this case 43981 = 0xabcd) to a char[], say, at the entry 0, the following code would produce the first 2 bytes of data in little endian, i.e. 0xcdab, when I'm trying to do the opposite thing:
char data[100];
int host_value = 43981; // 0xabcd
int net_value = HTON16(host_value);
data[0] = (net_value & 0xff00) >> 8;
data[1] = (net_value & 0xff);
My solution to the previous problem is just not using HTON16 on the host value, and operating with it as if my machine was big endian.
Also, in the same machine, when doing the following to write the same host value to data, it does produce data to have the two first byte set to 0xabcd:
*((unsigned short *)&data[0]) = HTON16(host_value);
I would like to understand why these two cases work differently. Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是这两行,
如果您在小型机器上运行
(net_value& 0xff)是第一个字符,如果您 使用位操作,应该是直接操作,无需致电Hton16
The problem is these two lines,
If you run on a little-endian machine,
if you use bit operations, it should be a direct operation, no need to call HTON16