C 为什么输出看起来像这样?

C 为什么输出看起来像这样?,c,struct,bit-manipulation,C,Struct,Bit Manipulation,我下面有一个c程序,我想按特定顺序发送一条32位消息,例如0x00000001 #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; };

我下面有一个c程序,我想按特定顺序发送一条32位消息,例如0x00000001

#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;
}
#包括
#包括
#包括
#包括
#包括
#包括
结构测试
{
uint16_t a;
uint16_t b;
};
int main(int argc,char const*argv[]
{
char-buf[4];
结构测试*ptr=(结构测试*)buf;
ptr->a=0x0000;
ptr->b=0x0001;
printf(“%x%x\n”,buf[0],buf[1]);//输出为0
printf(“%x%x\n”,buf[2],buf[3]);//输出为1 0
返回0;
}
然后我通过打印char数组中的值来测试它。我在上面的评论中得到了输出。输出不应该是0和0 1吗?但是[3]是最后一个字节吗?有什么我错过的吗


谢谢

因为它的小末端。请阅读以下内容:


要将它们转换为网络顺序,必须使用
htonl
(主机到网络长)和
htons
(主机到网络短)转换功能。收到后,您需要使用
ntohl
ntohs
功能将网络订单转换为主机订单。字节在数组中的放置顺序取决于您在内存中的放置方式。如果将它们放在四个独立的短字节中,则将省略endianness转换。您可以使用
char
type进行这种原始字节操作。

您的系统将数字存储为Windows将数据保持为“小端”,以便字节被反转。
有关更多信息,请参阅。

那么,当我从socket.h使用sendto()发送消息时,消息是什么样子的?它将是0x00000001或0x00000100?@cjk:您需要使用
htons
进行发送,这样您就不用知道确切的结尾了。