Thread: what does this mean: if ((i & 0x3) != 0)

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    269

    what does this mean: if ((i & 0x3) != 0)

    Hi all,

    I have some code I need to change and the code has some things like this:

    Code:
    for (size_t i = 0; i < numiters; i++)                                                                                                                                                               
    { 
        if ((i & 0x3) != 0)                                                                                                                                                                             
         {
            // do some stuff
         }
         else 
         {
             if ((i & 0x1c) != 0)
             {
                 // do some stuff
             }
          }
        /// do some stuff
    }
    What do these mean:
    if ((i & 0x3) != 0)

    and

    if ((i & 0x1c) != 0)

    Thanks!

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,616
    This is how you check a number's bits. 0x3 is 011 in binary. The statement (i & 0x3) being true means that i has the 2 least significant bits turned on. 0x1c is just another example but this time the bits are 011100 (again, least significant).

    As for what the bits actually mean, it really depends on you. Often what people will do when they want to communicate state through bit patterns is assign meanings to powers of two: this way several bits can be on, communicating that the variable is in multiple states at once.
    Last edited by whiteflags; 03-17-2017 at 06:47 PM.

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    4,131
    Quote Originally Posted by whiteflags View Post
    This is how you check a number's bits. 0x3 is 011 in binary. The statement (i & 0x3) being true means that i has the 2 least significant bits turned on. 0x1c is just another example but this time the bits are 011100 (again, least significant).

    As for what the bits actually mean, it really depends on you. Often what people will do when they want to communicate state through bit patterns is assign meanings to powers of two: this way several bits can be on, communicating that the variable is in multiple states at once.
    Has at least one of the 2 least significant bits turned on.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

Popular pages Recent additions subscribe to a feed

Tags for this Thread