pyt*_*iku 5 c struct bit-manipulation
我有交流计划下面,我想在一个特定的顺序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;
}
Run Code Online (Sandbox Code Playgroud)
然后我通过打印char数组中的值来测试它.我在上面的评论中得到了输出.输出不应该是0 0和0 1吗?既然但[3]是最后一个字节?我错过了什么吗?
谢谢!
导致它的小端.阅读: Endianness
要将它们转换为网络顺序,您必须使用htonl(主机到网络长)和htons(主机到网络短)转换功能.收到后,您需要使用ntohl和ntohs功能从网络转换为主机订单.字节放在数组中的顺序取决于将它们放入内存的方式.如果将它们作为四个单独的短字节放置,则将省略字节顺序转换.您可以使用char类型进行此类原始字节操作.
| 归档时间: |
|
| 查看次数: |
83 次 |
| 最近记录: |