2

Possible Duplicate:
Reference - What does this symbol mean in PHP?

I am working on some legacy code where I came across the following function:

function is_odd($number) {
   return $number & 1; // 0 = even, 1 = odd
}

I have never seen a method to check if a number is odd written like that before and am just trying to understand what they actually are doing.

Community
  • 1
  • 1
WhoaItsAFactorial
  • 3,538
  • 4
  • 28
  • 45

1 Answers1

7

& is a bitwise-and, it basically works so that for every bit that is 1 in both operands, it yields 1 in the resulting value and 0 for all other bits. If you convert any number to its bit representation, you quickly see that it's the lowest bit that determines whether a number is even or odd, for example:

   5 = 101
  10 = 1010
  13 = 1101
1030 = 10000000110

The lowest bit (the one on the very right, also called the least significant bit) is 1 for every odd number and 0 for every even number. Doing $n & 1 will always yield 0 for every other bit than the lowest bit (because the number 1 only has one bit, you can imagine that the rest of the bits are left-padded with 0 to match the length of the other operand). So basically the operation boils down to comparing the lowest bit of the operands, and 1 & 1 is 1, all other combinations are 0. So basically when the $n & 1 yields 1, it means the number is odd, otherwise it's even.

EDIT.

Here's a few examples to demonstrate how the bitwise-and works for the example values I gave earlier, the number in the parenthesis is the original decimal number:

  101 (5)
& 001 (1)
  ---
  001 (1) = true


  1010 (10)
& 0001 (1)
  ----
  0000 (0) = false


  1101 (13)
& 0001 (1)
  ----
  0001 (1) = true


  10000000110 (1030)
& 00000000001 (1)
  -----------
  00000000000 (0) = false

From this you can easily see that the result is only true when both operands' right-most bits are 1.

reko_t
  • 55,302
  • 10
  • 87
  • 77