反汇编windows htonl()函数

因为自己在系统内核写网络程序有时候需要调用htons htonl 这样的函数进行转换,但由于内核只能调用c运行库,别的API不能调用。自己也接触过一点汇编,从来没有去学过。看过老码识途这本书前几章,如是自己反编译试了一下,结果自己还真反出来,对于懂汇编的人确实非常容易。

 

ULONG myHtonl(ULONG i)
{
	ULONG eax,edx,ecx;
	eax = i;
	edx = i;
	edx = edx << 16;
	eax = eax & 0x0ff00;
	eax = eax | edx;
	edx = i;
	edx = edx & 0x0ff0000;
	ecx = i >> 16;
	edx = edx | ecx;
	eax = eax << 8;
	edx = edx >> 8;
	eax = eax | edx;
	return eax;
}

 变量就用寄存器的名字,这样避免混淆。 自己感觉这个代码是不是有点问题,他怎么没有判断自己系统是不是小端就进行转换了,如果自己电脑是高端怎么办呢?

后面看了网上一个人写模拟代码。

http://wxxweb.blog.163.com/blog/static/13512690020103145256909/

ypedef unsigned short int uint16;

typedef unsigned long int uint32;

 

// 短整型大小端互换

#define BigLittleSwap16(A)  ((((uint16)(A) & 0xff00) >> 8) | \

                                                 (((uint16)(A) & 0x00ff) << 8))

 

// 长整型大小端互换

#define BigLittleSwap32(A)  ((((uint32)(A) & 0xff000000) >> 24) | \

                                                 (((uint32)(A) & 0x00ff0000) >> 8) | \

                                                 (((uint32)(A) & 0x0000ff00) << 8) | \

                                                 (((uint32)(A) & 0x000000ff) << 24))

 

// 本机大端返回1,小端返回0

int checkCPUendian()

{

       union{

              unsigned long int i;

              unsigned char s[4];

       }c;

 

       c.i = 0x12345678;

       return (0x12 == c.s[0]);

}

 

// 模拟htonl函数,本机字节序转网络字节序

unsigned long int HtoNl(unsigned long int h)

{

       // 若本机为大端,与网络字节序同,直接返回

       // 若本机为小端,转换成大端再返回

       return checkCPUendian() ? h : BigLittleSwap32(h);

}

 

// 模拟ntohl函数,网络字节序转本机字节序

unsigned long int NtoHl(unsigned long int n)

{

       // 若本机为大端,与网络字节序同,直接返回

       // 若本机为小端,网络数据转换成小端再返回

       return checkCPUendian() ? n : BigLittleSwap32(n);

}

 

// 模拟htons函数,本机字节序转网络字节序

unsigned short int HtoNs(unsigned short int h)

{

       // 若本机为大端,与网络字节序同,直接返回

       // 若本机为小端,转换成大端再返回

       return checkCPUendian() ? h : BigLittleSwap16(h);

}

 

// 模拟ntohs函数,网络字节序转本机字节序

unsigned short int NtoHs(unsigned short int n)

{

       // 若本机为大端,与网络字节序同,直接返回

       // 若本机为小端,网络数据转换成小端再返回

       return checkCPUendian() ? n : BigLittleSwap16(n);

}

  看了他自己添加了判断,我估计windows系统估计通过宏进行替换了honts 这些函数,如果是小端 定义转换内容,如是高端高端就定义直接返回即可了。这种做法windows最喜欢这样写代码了。

转载于:https://www.cnblogs.com/c-study/p/3725739.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值