繁体   English   中英

htonl打印垃圾价值

[英]htonl printing garbage value

变量“值”是uint32_t

    value = htonl(value);

    printf("after htonl  is %ld\n\n",value);

    This prints -201261056

    value = htons(value);

    printf("after htons  is %ld\n\n",value);

    This prints  62465

请说明可能是什么原因?

主机顺序是您的机器正确理解数据的顺序(假设您的机器是低端字节序)。 网络顺序是Big Endian,系统无法正确理解。 这就是所谓的垃圾值的原因。

因此,基本上,代码没有任何内容。 :)

Google“ Endianness”可获取有关Big Endian和Little Endian的所有详细信息。

提供更多信息,在大字节序中,第一个字节或最低地址将具有最高有效字节,而在小字节序中,在同一位置,将出现最低有效字节。 因此,当您使用htonl时,您的第一个字节现在将包含最高有效字节,但是您的系统会认为它是最低有效字节。

考虑Wikipedia示例,大端数字的十进制数1000(十六进制3E8)将为03 E8,小端数字的十进制数将为E803。现在,如果将03 E8传递给一台小型计算机,它将被视为十进制59395。

我想您输入的是500,不是吗?

500以小尾数顺序为2 * 8 + 2 * 7 + 2 * 6 + 2 * 5 + 2 * 4 + 2 * 2或0x00 0x00 0x01 0xF4

TCP / IP使用大字节序。 因此,在htonl之后,序列为0xF4 0x01 0x00 0x00

如果将其打印为有符号整数,则由于第一位为1,则它为负数。 负数被视为补数,值是-(2 * 27 + 2 * 25 + 2 * 24 + 2 * 23 + 2 * 22 + 2 * 21 + 2 * 20 + 2 * 19 + 2 * 18 + 2 * 17 + 2 ** 16)== -201261056

htonl() and htons()是用于将数据从主机的字节性转换为网络字节性的函数。

网络使用big-endian。 因此,如果您的系统是X86,则它是低端字节序。

主机到网络的字节顺序(长数据)是htonl()。 即将32bit值转换为网络字节顺序。

主机到网络的字节顺序(短数据)为htons()。 即将16bit值转换为网络字节顺序。

该示例程序演示htonl()的工作方式以及在htons()函数中使用32位值的效果。

#include <stdio.h>
#include <arpa/inet.h>

int main()
{
   long data = 0x12345678;
   printf("\n After htonl():0x%x  , 0x%x\n", htonl(data), htons(data));
   return 0;
}

它将在X86_64上的After htonl():0x78563412 , 0x7856打印。

参考:

http://en.wikipedia.org/wiki/Endianess

http://msdn.microsoft.com/en-us/library/windows/desktop/ms738557%28v=vs.85%29.aspx

http://msdn.microsoft.com/en-us/library/windows/desktop/ms738556%28v=vs.85%29.aspx

@halfelf>I jut want to put my findings.I just tried the below program with the same 
value 500.I guess you have mistakenely mentioned output of LE as BE and vice versa
Actual output i got is 0xf4 0x01 0x00 0x00 as little Endian format.My Machine is 
LE
#include <stdio.h>
#include <netinet/in.h>
/* function to show bytes in memory, from location start to start+n*/
void show_mem_rep(char *start, int n)
{
    int i;
     for (i = 0; i < n; i++)
      printf(" %.2x-%p", start[i],start+i);
     printf("\n");
}

/*Main function to call above function for 0x01234567*/
int main()
{
  int i = 500;//0x01234567;
   int y=htonl(i); --->(1)
   printf("i--%d , y---%d,ntohl(y):%d\n",i,y,ntohl(ntohl(y)));
   printf("_------LITTLE ENDIAN-------\n");
   show_mem_rep((char *)&i, sizeof(i));
   printf("-----BIG ENDIAN-----\n");/* i just used int y=htonl(i)(-1) for reversing 
   500 ,so that
   i can print as if am using a BE machine. */

   show_mem_rep((char *)&y, sizeof(i));

   getchar();
   return 0;
  }
output is 
i--500 , y----201261056,ntohl(y):-201261056
_------LITTLE ENDIAN-------
 f4-0xbfda8f9c 01-0xbfda8f9d 00-0xbfda8f9e 00-0xbfda8f9f
 -----BIG ENDIAN-----
  00-0xbfda8f98 00-0xbfda8f99 01-0xbfda8f9a f4-0xbfda8f9b

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM