# reading certain bits from a byte

• 07-18-2002
Unregistered
reading certain bits from a byte
pretend my char is 85 (01010101)
if I only want to read the last 3 bits (010...) from the char and use it as a separate value, how do I do it?
since 010 the result would be 2, I know the value of the bits are found at 0x80, 0x40, and 0x20.
any one know how to do this?
• 07-18-2002
SilentStrike
Combination of bit masking and shifting.

Code:

```#include <iostream> int main() {         int test=85;         std::cout << ((test & (0x80 | 0x40 | 0x20)) >> 5) << std::endl;         return 0; }```
0x80 | 0x40 | 0x20 is 0xE0, just shown like that to see where it comes from.
• 07-18-2002
fletch
hmmm....
SilentStrike,

How does '>> 5' work?

I understand what you're doing up the point of >> 5. The first part, (test & (0x80 | 0x40 | 0x20)), should return 01000000b. Judging by the output, I'm guessing that '>> 5' shifts everything to the right by 5 bits.

fletch
• 07-19-2002
Shiro
You can use bitfields to manipulate specific bits:

Code:

```#include <iostream> using namespace std; typedef struct {     unsigned int bit0:1;     unsigned int bit1:1;     unsigned int bit2:1;     unsigned int bit3:1;     unsigned int bit4:1;     unsigned int bit5:1;     unsigned int bit6:1;     unsigned int bit7:1; } bitfield_s; typedef union {     bitfield_s bitfield;     unsigned char byte; } byte_u; int main () {     byte_u var;     var.byte = 0xBA;     cout << "bit 0: " << var.bitfield.bit0 << endl;     cout << "bit 6: " << var.bitfield.bit6 << endl;         return 0; }```
• 07-19-2002
Cshot
Quote:

I understand what you're doing up the point of >> 5. The first part, (test & (0x80 | 0x40 | 0x20)), should return 01000000b. Judging by the output, I'm guessing that '>> 5' shifts everything to the right by 5 bits.
That's exactly what it does.
• 07-21-2002
Unregistered
okay, but what if I only want to read the first 3 bits of the byte (0x01, 0x02, and 0x04) and use it as a separate value?
• 07-21-2002
fletch
Code:

```int test1, test2; test1 = 85; test2 = ((test1 & 0xE0) >> 5); std::cout << "test1 = " << test1 << std::endl;        // 85 std::cout << "test2 = " << test2 << std::endl;        // 2```