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
?
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
?
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.
Here, &
is the bitwise AND operator.
a&1
(or, rather a & 1
) checks the LSB of a
to be SET or not.