关于htonl的源码 [英] About the source code of htonl

查看:85
本文介绍了关于htonl的源码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我指的是以下代码:

u_int32_t htonl(u_int32_t x)
{
#if BYTE_ORDER == LITTLE_ENDIAN
    u_char *s = (u_char *)&x;
    return (u_int32_t)(s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]);
#else
    return x;
#endif
}

例如:

unsigned int x = 0x01020304

在小结局系统中:

s[0] = 0x04, s[1] = 0x03, s[2] = 0x02, s[3] = 0x01

然后返回:

(u_int32_t)(s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]);

返回值,例如:

u_int32t_t result = (u_int32_t)(s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]);

在系统内存中:

u_char *r = (u_char *)&result

所以:

r[0] = 0x04, r[1] = 0x03, r[2] = 0x02, r[3] = 0x02

这是正确的吗?

推荐答案

htonl 的目的是将值表示转换为网络字节序——大端.假设您在英特尔机器上工作并且您的字节顺序是小端(执行 if 语句中的代码).您可以编写一个虚拟代码来检查您是否理解它是如何工作的:

The purpose of htonl is to convert value representation to network byte order - big endian. Let's suppose that you're working on intel machine and your byte order is little endian (the code in if statement is executed). You could write a dummy code that checks your understanding how it works:

#include<stdio.h>
#include <stdlib.h>
int main()
{
    u_int32_t x = 16909060;  //0x01020304
    u_char* s = (u_char*)&x;
    printf("%x\n",x);
    printf("s[0]: %x\n",s[0]);
    printf("s[1]: %x\n",s[1]);
    printf("s[2]: %x\n",s[2]);
    printf("s[3]: %x\n",s[3]);
    printf("s[0] << 24: %x\n", s[0] << 24);
    printf("s[1] << 16: %x\n", s[1] << 16);
    printf("s[2] << 8: %x\n", s[2] << 8);
    printf("final: %x\n", s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]);

    return 0;
}

输出:

1020304
s[0]: 4
s[1]: 3
s[2]: 2
s[3]: 1
s[0] << 24: 4000000
s[1] << 16: 30000
s[2] << 8: 200
final: 4030201

OR 运算符具有以下真值表:

OR operator has following truth table:

a b out
0 0  0
0 1  1
1 0  1
1 1  1

所以这是计算

0000 0100 0000 0000 0000 0000 0000 0000 |   //s[0] << 24
0000 0000 0000 0011 0000 0000 0000 0000 |   //s[1] << 16
0000 0000 0000 0000 0000 0010 0000 0000 |   //s[2] << 8
0000 0000 0000 0000 0000 0000 0000 0001 =   //s[3]
_________________________________________

0000 0100 0000 0011 0000 0010 0000 0001     

总结一下,不同字节顺序的 0x01020304:

To summarize, 0x01020304 in different byte orders:

  • little endian:04 03 02 01(LSB 的地址最小)
  • big endian:01 02 03 04(MSB 的地址最小)

这篇关于关于htonl的源码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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