# c++ - Advance bit manipulation, leaving empty bits in any pos

I have two chars, `a` and `b`. I am trying to store a `15 bit int` in those chars, but I must leave the 8th bit of the first char untouched.

I know how to do this without the gap on the 8th char:

``unsigned int num = 32767;unsigned char a = num;unsigned char b = (num & 0xFF00) >> 8;cout << "The num is: " << (unsigned int)a + ((unsigned int)b << 8);``

Can someone please help me understand how this works, so I can learn to leave any bit or bits empty in any position?

I'm assuming by "eighth bit", you mean the most significant bit... Try:

``````unsigned int num = 32767;
unsigned char a = 0, b = 0;

a &= 0x80;                               // Preserve only the MSB of a
a |= (num & ((1 << 7) - 1));             // Bit-wise OR the seven LSBs of num
b  = (num & (((1 << 8) - 1) << 7)) >> 7; // Set b equal to the remaining eight bits of num.

cout << "The num is: " << (unsigned int)(a & 0x7F) + ((unsigned int)b << 7);
``````

Here's the key... If you want to make a bit mask that's m bits long starting n bits from the right, you can use this expression:

``````mask = ((1 << m) - 1) << n;
``````

Then, you can just use the & operator to set every bit not in the mask to 0, >> to shift the result, and = or |= to set the bits appropriately.

Alternative

Here's an alternative solution in case you meant least-significant bit instead of most-significant bit:

``````unsigned int num = 32767;
unsigned char a = 0, b = 0;

a &= 0x01;                               // Preserve only the MSB of a
a |= (num & ((1 << 7) - 1)) << 1;             // Bit-wise OR the seven LSBs of num
b  = (num & (((1 << 8) - 1) << 7)) >> 7; // Set b equal to the remaining eight bits of num.

cout << "The num is: " << (unsigned int)((a & 0xFE) + ((unsigned int)b << 7);
``````