Search code examples
c++bit-fieldscan-bus

How to Concatenate two BitFields


I have two seperate bitfields that make up a "Identity" field that are 11 + 18 bits in length (29 bits total).

In the bitfield they are of the expected size:

header a;
memset(a.arr, 0, sizeof(a.arr));
a = {0xA0,0xA0,0xA0,0xA0,0xA0,0xA0,0xA0,0xA0,0xA0}; // 1010 0000

cout << hex << a.BID << endl; // 010 0000 1010 -> 20a
cout << hex << a.IDEX << endl; // 00 1010 0000 1010 0000 -> a0a0

and what I need to do is combine these fields into a 29-bit segment, e.g. 010 0000 1010 00 1010 0000 1010 0000.

When attempting to concatenate the two bitfields however the result is not what I expect:

int BID = a.BID;
int IDEX = a.IDEX;    
int result = (BID<<11) | IDEX;
cout << BID << endl;
printf("%x %d",result, result);  // -> 10f0a0 (21 bits) where I expect 828A0A0 (29 bits)

It's important for me to have all 29 bits as within this 29-bit field there's various subfields and I was going to take this output and put it through another bit-field to resolve those subfields.

Would you be able to assist in how I could combine BID and IDEX mentioned above into one combined bitfield of 29 bits? Unfortunately they have two bits inbetween the BID and IDEX fields another in the header that are ignored which is why I cannot just set my bitfield to 29 bits.


Solution

  • You should shift 18 bits first and then do the OR. For example:

    int result = (BID<<18) | IDEX;

    Otherwise you are overwriting the first block. What you are doing here is shifting 11 bits and then ORing with 18 bits which corrupts the first 11 bits indeed.