Search code examples
cperformancebit-manipulationreturn-valuebitwise-and

Which is better, double negation or bitshift?


I need a boolean-type function which determines if a bit, in a variable's bit representation, is set or not.

So if the fourth bit of foo is what I want to inspect, I could make the function return

!!(foo & 0x8)  //0x8 = 1000b

or

(foo & 0x8) >> 3

to get either 0 or 1.

Which one is more desirable in terms of performance or portability? I'm working on a small embedded system so a little but detectable cost difference still matters.


Solution

  • This solution

    return (foo & 0x8) >> 3;
    

    is the worst. If for example the magic constant 0x8 will be changed then you also need to change the magic constant 3. And moreover it can occur such a way that applying the operator >> will be impossible for example when you need to check more than one bit.

    If you want to return either 1 (logical true) or 0 (logical false) I think that it will look more clear if to write

    return (foo & 0x8) != 0;
    

    or

    return (foo & 0x8) == 0x8;
    

    For example if instead of the magic constant 0x8 you will use a named constant (or variable) as for example MASK then this return statement

    return ( foo & MASK ) == MASK; 
    

    will not depend on the value of MASK.

    Pay attention to that these two return statements

    return (foo & MASK) != 0;
    

    and

    return ( foo & MASK ) == MASK; 
    

    are not equivalent. The first return statement means that at least one bit is set in the variable foo while the second return statement means that exactly all bits corresponding to bits in MASK are set.

    If the return type of the function is _Bool (or bool defined in <stdbool.h>) and you need to check whether at least one bit is set according to the bit mask then you can just write

    return foo & MASK;