copying bitfields to buffer

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;

unsigned char *buffer;
pkt->pack(buffer);
return 0;
}
Something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <cstdint>
#include <bitset>
#include <cstring>
#include <algorithm>

struct bits
{
    unsigned sender : 16 ;
    unsigned res : 16 ;
    unsigned e : 12 ;
    unsigned f : 4 ;
};

int main()
{
    const bits b { 0xffff, 3, 2, 1 } ;

    const std::uint32_t res = b.res ;
    const std::uint32_t e = b.e ;
    const std::uint32_t f = b.f ;

    std::uint32_t buff = ( res << 16 ) | ( e << 4 ) | f ;
    // test it
    std::cout << std::bitset<32>(buff) << '\n' ;

    // copy it
    std::uint8_t byte_buff[4] ;
    std::memcpy( byte_buff, &buff, sizeof(buff) ) ;

    // check endianness
    for( std::uint8_t b : byte_buff ) std::cout << std::bitset<8>(b) << ' ' ;
    std::cout << '\n' ;

    // if needed, swap bytes
    std::swap( byte_buff[0], byte_buff[3] ) ;
    std::swap( byte_buff[1], byte_buff[2] ) ;

    for( std::uint8_t b : byte_buff ) std::cout << std::bitset<8>(b) << ' ' ;
    std::cout << '\n' ;
}


http://ideone.com/rb9Azj
Topic archived. No new replies allowed.