2012-10-17 163 views
5

我有一個c程序下面,我想發出一個特定的順序Eg.0x00000001 32位消息。爲什麼輸出看起來像這樣?

#include <unistd.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <sys/types.h> 
#include <stdint.h> 

struct test 
{ 
    uint16_t a; 
    uint16_t b; 
}; 

int main(int argc, char const *argv[]) 
{ 
    char buf[4]; 
    struct test* ptr=(struct test*)buf; 
    ptr->a=0x0000; 
    ptr->b=0x0001; 
    printf("%x %x\n",buf[0],buf[1]); //output is 0 0 
    printf("%x %x\n",buf[2],buf[3]); //output is 1 0 
    return 0; 
} 

然後我通過打印出char數組中的值來測試它。我在上面的評論中得到了輸出。不應該輸出0 0和0 1?因爲[3]是最後一個字節?有什麼我錯過了嗎?

謝謝!

回答

7

導致其小端。閱讀: Endianness

對於他們翻譯成網絡秩序,你必須使用htonl(主機到網絡長)和htons(主機到網絡短)轉換功能。收到之後,您需要使用ntohlntohs函數將網絡轉換爲主機順序。字節放置在數組中的順序取決於你如何將它們放入內存中的方式。如果你把它們作爲四個獨立的短字節,你將省略字節序轉換。您可以使用char類型來處理這種原始字節操作。

+0

所以當我從socket.h使用sendto()發送消息時,消息是怎麼樣的?它會是0x00000001或0x00000100? – kun

+0

@cjk:你需要使用'htons'進行發送,它知道你的確切排序。 – Vlad

0

Windows將保留數據爲「小尾」,所以字節逆轉。 有關更多信息,請參閱Endiannes

相關問題