问题描述:

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);
```

您可能感兴趣的文章：

- android - I Want animation between activities like skout app
- JSON and Django fields
- Check if a JavaScript function is a method for a jQuery element
- node.js - find all documents using mongoose
- java - JAR in EXE mode - How to add all library jar to executable?
- php - Reading a specific line from a text file
- clr - Any implementation of an Unrolled Linked List in C#?
- Finding Hudson Log Files
- Forward to a payment-gateway together with POST data using cURL (or any other PHP server side solution)
- WCF in Winforms app - is it always single-threaded?

随机阅读：

**推荐内容**-

**热点内容**