Re: simple bit question by muchan
muchan
Tue May 11 09:29:42 CDT 2004
Niklas wrote:
> I'm still trying to get this to work properly.
> I want to check Information[0] bit 0
> and Information[1] bit 4
>
> (bit 1-3 of Information[1] can be 010 and 001, but that is not relevant to
> me at this point)
>
> these are my cases
> if (Information[0] bit 0 == 0 && Information[0] bit 4 == 1)
> doFirstThing();
> if (Information[0] bit 1 == 1 && Information[0] bit 4 == 1)
> doSecondThing();
> if (Information[0] bit 1 == 1 && Information[0] bit 4 == 0)
> doThirdThing();
>
> so first I think I can do
> if (Information[0] & 0x0 && Information[1] & 0x8)
>
Now I'm not sure any more what you meant with "bit 0" and "bit 3"...
but if (a_value & 0x0) doesn't work. it's always 0x0.
> second statment
> if (Information[0] & 0x1 && Information[1] & 0x8)
> is that correct?
> but the third. how do I know if bit 4 is 0?
>
> thanks
>
You mask the bit and the result is 0, then the bit is 0.
(suppose your "bit 4" means binary 10000, 0x10)
if ( Information[0] & 0x10 == 0 )
First, I think you should check what bit wise & operator does.
Second, I think you should make a utility functions returning bool like:
bool bit_0(insigned char uc) { return ( uc & 0x01 ); } // binary 0000 0001
bool bit_1(insigned char uc) { return ( uc & 0x02 ); } // binary 0000 0010
bool bit_2(insigned char uc) { return ( uc & 0x04 ); } // binary 0000 0100
bool bit_3(insigned char uc) { return ( uc & 0x08 ); } // binary 0000 1000
bool bit_4(insigned char uc) { return ( uc & 0x10 ); } // binary 0001 0000
bool bit_5(insigned char uc) { return ( uc & 0x20 ); } // binary 0010 0000
bool bit_6(insigned char uc) { return ( uc & 0x40 ); } // binary 0100 0000
bool bit_7(insigned char uc) { return ( uc & 0x80 ); } // binary 1000 0000
then
if ( bit_0(uc1) == false && bit_4(uc2) == true) ...
if ( bit_0(uc1) == true && bit_4(uc2) == true) ...
if ( bit_0(uc1) == true && bit_4(uc2) == false) ...
muchan (don't know if 0x01 is "bit 0" or "bit 1" yet...)