2012-10-17 162 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

相关问题