Topic: Bitwise Operators

I'm trying to learn to love C and all it's low level goodness.  That means coming to know and love, wait for it...  the bitwise operators.  For the life of me I cannot get this function (returns 1 if any bit in a word is set to 0 ) to work the way I would like it too.

int any_bit_off(unsigned x) {

         unsigned char *t, *e;
         for(t = &x, e = (&x + sizeof(x)); t != e; ++t) {
                 if( (*t & 0) )
                         return 1;
         }

         return 0;
}

What I think this ought to be doing is using byte pointers (unsigned chars, correct?) to walk through the word and comparing each bit of each byte using the & bitwise operator.  If a "off bit" is found it should return one, otherwise the default return value is zero (no off bits where found).  It unfortunately returns zero when I pass it 'unsigned z = 0xFFFFFFFF' which should have no 'off' bits in it.  I think my mask is in the if condition is wrong but I'm not sure how or why.  K&R are unusually terse on this point.  Perhaps someone here can explain.

Thank you.

Re: Bitwise Operators

Your function will always return 0, because *t & 0 always returns zero. Any number ANDed with 0 is always 0.

May I suggest a much easier way to solve the problem:

int any_bit_off(unsigned x) {
        return (x & 0xFFFFFFFF) != 0xFFFFFFFF;
}

Re: Bitwise Operators

Thanks!  I ended up with this version which in theory is word-size independent.

int any_bit_off(unsigned x) {
    return ~x && 1;
}

Re: Bitwise Operators

Ah, that's smart too. The && 1 bit is redundant though.