我有一個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]是最後一個字節?有什麼我錯過了嗎?
謝謝!
所以當我從socket.h使用sendto()發送消息時,消息是怎麼樣的?它會是0x00000001或0x00000100? – kun
@cjk:你需要使用'htons'進行發送,它知道你的確切排序。 – Vlad