1. ## Bitfield

Hi Guys,

Question on a BitField. How will I check the sixth bit in a six bits storage? For example

Code:
```struct BITF
{
unsigned Bits:6;
unsigned :2;
};
struct BITF Buffer;
unsigned D;
D = (unsigned *)&Buffer;
*D = 0x04;
if( Buffer.Bits & ??? )
...```
I know, i will have to use bit mask to check the sixth bit.

0x04
0000 0100
Buffer.Bits ==> 0000 01

how will i check the sixth bit ( LSB == 1 )?

thanks guys!

~ssharish

2. Check it the same way you check the 6th bit of any integer.
Code:
```struct BITF b;
...
if( b.Bits & (1<<5) )```

Quzah.

3. This is a bit confusing. When I do the following way.

Code:
```struct BITF
{
unsigned Bits:6;
unsigned Bits2:6;
unsigned :4;
};
struct BITF Buffer;
unsigned D;
D = (unsigned *)&Buffer;
*D = 0x0421;
if( Buffer.Bits & (8>>2)) // This would give me the right results; Thanks Quzah
...```
But when i try o do this
Code:
`if( Buffer.Bits2 & 0x08) // This is not giving me the right answer`
0x0421

0000 01 | 00 0010 | 0001
Bits = 0000 01
Bits2 = 00 0010

What am I doing wrong?

Thanks a lot!

~ssharish

4. 0x0421 doesn't mean "set the first three bits. And 8 right shifted twice is just 2. I'm not sure you know what you're trying to do. Or at least, you aren't explaining what you're trying to do very well.

Quzah.

5. Apologies, for not being clear.

Think 0x0421 is some buffer value which we got over the network. From the buffer value extract the first 6 bits.

So for example 0x0421 in binary would look as follow

0000 0100 0010 0001

Now I need the first 6 bits to be int Buffer.Bits and the next Six bits in Buffer.Bits2 and hence the bitfield along the structure.

Now then, assuming all bits set and initialised to the right values. I can now access the first six bits by just Buffer.Bits.

I need to check if the LSBit in the 6 bits is set. depending on that I'll have to do some further processing.

I tried my best. Please let me know if i missed out something.

Thanks Quzah!

~ssharish

6. Why isn't checking LSB just
Code:
`(whatever & 1)`
?

7. Code:
```union u
{
unsigned int big;
struct
{
unsigned int firstsix:6;
unsigned int nextsix:6;
:4;
} s;
};```
You could always use a union. Or just mask off the six you need:
Code:
```unsigned int foo = 0x0124;
...
y = (foo & ((1<<6)-1); /* or just foo & 63 */```

Quzah.

8. Yeah masking is the probably very ideal. But the complication here is the buffer value is huge instead of just 0x0421.

Really its something like 0x04215435432534435435432 and hence i decided to go for structure representation.

ssharish

9. Originally Posted by tabstop
Why isn't checking LSB just
Code:
`(whatever & 1)`
?
Seconded!

10. Code:
`bit6 = (whatever & 32) >> 5;`