2

In some c++ code I have seen that someone using a statement like

while(a) { //here a is an integer variable
    if(a&1) {
        //some expression
    }
}

now my question is what is the meaning of a&1 ?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
SwadhIn
  • 717
  • 1
  • 9
  • 19

2 Answers2

4

It checks if a number is odd using bitwise operations. The last bit in a binary number is the ones place (or the 2^0 place). All odd numbers are going to have this bit turned on; it is what makes them odd. Therefore, by checking if a number has its last bit on (which is what & 1 does), you are actually checking whether or not it is odd. Since it uses bitwise operations, it is considerably faster than using modulo 2 for this purpose.

pzp
  • 6,249
  • 1
  • 26
  • 38
4

Here, & is the bitwise AND operator.

a&1 (or, rather a & 1) checks the LSB of a to be SET or not.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261