# Thread: Accessing a specific bit

1. ## Accessing a specific bit

I want to know if there's a way I can access a specific bit in a byte. Example, a byte looks like this: 00001001. What if I want to access 00001001, end test whether it's true or false.

I've tried using bit-shifting to the left, with the value of the bit's spot from the end-1, in this case: << 3, which results in 01001000. and then shifting >> 7, which results in that the specific bit is the only one left.

This doesn't work though, because the bits shifted away come back. The only explanation I can find to this is that they are passed over to the next byte. I tried this with int though, which is only one byte long, right?

Anyway, can I make this method work, or do it in an easier way?

2. Awwwwww! How stupid of me! If an int would be a byte long, the maximum value would be 256! Anyway, the problem remains.

4. Try using the shift as you did, but '&' the value with 1 afterwards

IE

00011001 >> 3 = 00000011

00000011 & 00000001 = 00000001

now if that == 1...the bit was set.

5. Or map the variable onto a bitfield with pointer conversion. Or just use a union with a bitfield in it.

Code:
```typedef union
{
bitfield_t      my_bitfield;
unsigned int    my_int;
} bits;

bits my_var;

// Assign the value
my_var.my_int = another_var;

// Access a single bit
my_bit = my_var.my_bitfield.bit_5;```

6. You could shift, and not even have to use a bit mask - if the resulting, shifted number is odd, then that bit was initally set...

7. You could also replace "& 1" with "| 0", right?

8. Bah... all this bit shifting and masking? Just mask the value using and, if the result is not zero then the bit was set, otherwise it was not set.
Code:
```const int iBitOneMask =   0x00000001;
...
...
...
...
...
...
bool bBitWasSet;
int iValue;
...
...
...
// Test if bit three of iValue was set.
if( iValue & iBitThreeMask ) bBitWasSet = true;
else bBitWasSet = false;
...
...
...
// Test if bit eight of iValue was set.
if( iValue & iBitEightMask ) bBitWasSet = true;
else bBitWasSet = false;```
Wouldn't that work? No bit shifting needed.