views:

103

answers:

3

Possible Duplicate:
Check if a number is non zero using bitwise operators in C.

Hello everyone,

I am working on a project and I need a little help with a function. We need to write a function that performs the logical not, !, using only the following bitwise operators:

~ & ^ | + << >>

I'm not even sure where to begin.

+1  A: 

If you can assume that true = 1 and false = 0, then this might do the trick:

bool
not(bool x) {
    bool not_x = x ^ true;
    return not_x;
}
Jeremy W. Sherman
+1  A: 

I think to start you want you'll want to clarify the question. It sounds like you're wanting at a function that will return 0 if any of the bits in a word are "1", and something other than 0 if all the bits are zero. Assuming a 32bit word "a" you could do something like:

na1 = ~a;
shifted_na1 = na1 >> 1;
na2 = shifted_na1 & na1; /* any sequence of zeros is now 2 bits long */
shifted_na2 = na2 >> 2;
na3 = shifted_na2 & na2; /* any sequence of zeros is now 4 bits long */
shifted_na3 = na3 >> 4;
na4 = shifted_na3 & na3; /* any sequence of zeros is now 8 bits long */
shifted_na4 = na4 >> 8;
na5 = shifted_na4 & na4; /* any sequence of zeros is now 16 bits long */
shifted_na5 = na5 >> 16;
final = shifted_na5 & na5; /* any sequence of zeros is now 32 bits long */
really_final = final & 1;
mjhm
logical ! should return 1, not 0xffffffff for 0 argument.
blaze
right, I had another error as well.
mjhm
+1  A: 

Logical not returns 0, if value is not zero, 1 otherwise. Assuming 32-bit int:

int not_func(int v) {
    /* compress value to single bit */
    int p = (v >> 16) | v;
    p = (p >> 8) | p;
    p = (p >> 4) | p;
    p = (p >> 2) | p;
    p = (p >> 1) | p;

    p ^= 1;
    return (p & 1);
}
blaze