i want to copy the bitfields to a buffer but i am not able to do it using memcpy. the first commented statement copies all elements of structure to buffer, but i dnt want to copy all the 4 elements, what if dnt want to put the "sender" in the buffer what change do i need to make in a statement
memcpy(buffer, &Header,8);
also if i try to copy each element individually to buffer, compiler complaints that these statements are not valid for bitfields...help me out
class myclass
{ public:
struct Header
{
unsigned short sender;
unsigned short Res;
unsigned short e:12;
unsigned short f:4;
}Header;
int pack(unsigned char *&buffer)
{
int bufferlength=8;
buffer = (unsigned char *)malloc(bufferlength);
memcpy(buffer, &Header,8);//this copies all elements to buffer
memcpy(buffer,&Header.Res,2); //this is ok
memcpy(buffer+2,&Header.e,sizeof(Header.e)); //gives error because & and sizeof is not valid for bitfields memcpy(buffer+2+sizeof(Header.e),&Header.f,sizeof(Header.f));//also error
return 0;
}
};
int main()
{
myclass *pkt= new myclass();
pkt->Header.sender=0;
pkt->Header.Res=10;
pkt->Header.e=90;
pkt->Header.f=2;