字节流及字节对齐

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33048069/article/details/79278343
#include <iostream>
#pragma pack(push,4)
struct MyStruct
{
   unsigned char a;//
   unsigned int b; //到这里是,加起来等于unsigned int 字节的倍数
   unsigned char Cbuffer[10];//char没有字节对齐
   unsigned int d;
  
};
#pragma pack()


void EnCodePack(unsigned char*cSendBuff,void *pSrc)
{
    int pos =0;
    MyStruct *ptr = (MyStruct *)(pSrc);
    *(cSendBuff+pos) =ptr->a;
    pos+=sizeof(ptr->a);
    pos+=3;//字节偏差最大为1
    *((unsigned int*)(cSendBuff+pos)) = ptr->b;


    pos+=sizeof(ptr->b);


    memcpy(cSendBuff+pos,ptr->Cbuffer,10);
    pos+=sizeof(ptr->Cbuffer);
    pos+=2;


    *((unsigned int*)(cSendBuff+pos)) = ptr->d;
    pos+=sizeof(ptr->d);
}


//然后所有的pos加起来就是字节对齐的倍数


int main()
{
    unsigned char buffer[100] ={0};
    MyStruct st;
    int iDataSize = sizeof(st);
    st.a ='3';
    st.b =100;
    memcpy(st.Cbuffer,"123456789",10);
    st.d =200;


    EnCodePack(buffer,&st);


    MyStruct*ptr = (MyStruct*)(buffer);
    int xx =10;
}

猜你喜欢

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