我有一个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