簡體   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