结构体转二进制流的写法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33048069/article/details/79269782
比如这种结构体,按4byte对齐

struct Tstr

{
    char a;
    unsigned int   d;
    int c;
};
void EnCode(unsigned char *pBuferr,void *pVoid)//前者的参数发送的buff,后面的参数数据源
{
    int iPos =0;
    Tstr*ptr = (Tstr*)(pVoid);
    *(pBuferr+iPos) =ptr->a;
    iPos+=sizeof(ptr->a);

  iPos+=3;//补齐三个字节

  *(unsigned int*)(pBuferr+iPos) = ptr->d;//若这里涉及到大小端,读跟上htonl ntohl函数  ,因此也就是这样写*(unsigned int*)(pBuferr+iPos) = htonl(ptr->d);
    iPos+=sizeof(ptr->d);
    *(int*)(pBuferr+iPos) = ptr->c;
    iPos+=sizeof(ptr->c);
}

对于按多少字节对齐:

解决的思路是;

1.弄清楚int ,float double等常用数据类型占用多少字节.

2.查结构体里面的最大的字节是多大,然后然后最大的字节去算偏移量.

3 最后算出来正好是按多少字节的倍数.


猜你喜欢

转载自blog.csdn.net/qq_33048069/article/details/79269782