Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 3 of 3

Thread: Using Bitwise and in If statements...

  1. #1

    Using Bitwise and in If statements...

    All,
    A quick question for the group. I am using a byte as 8 booleans and in some of my "IF" statements, I am reading certain bits to be "true" per the example below.
    Code:
    if(bit_bool & (1<<0)) {do_something();}
    In the instance where you would want to check if the bit boolean is false condition, would you write as such...
    Code:
    if(!(bit_bool & (1<<0)))  {do_nothing();}
    or would the code below have to be substituted...
    Code:
    if(bit_bool & (1<<0) != true) {do_nothing();}
    I am currently not at a computer to test this so, please forgive that aspect.

    Thanks
    Bryan

  2. #2
    Senior Member+ Frank B's Avatar
    Join Date
    Apr 2014
    Location
    Germany NRW
    Posts
    5,436
    false and true are defined as
    Code:
     #ifdef __cplusplus
        typedef bool boolean;
    #else
        typedef uint8_t boolean;
        #define false 0
        #define true !false
    #endif
    in wiring.h in the core.
    Goes back to this pull request: https://github.com/arduino/Arduino/pull/2151

  3. #3
    Senior Member
    Join Date
    Nov 2012
    Posts
    1,021
    I think it is better not to think of these as boolean quantities because they aren't. Treat them as individual bit "flags" in a byte. If you want to test if bit N is set, test whether it is non-zero:
    Code:
    if(bit_bool & (1<<N))  {do_nothing();}
    or if you want to a bit more explicit about it:
    Code:
    if((bit_bool & (1<<N)) != 0) {do_nothing();}
    To test if it is zero use this:
    Code:
    if((bit_bool & (1<<N)) == 0) {do_nothing();}
    Pete

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •