Archive for July, 2006

Odd and Even Numbers

Sometimes its necessary to find out whether a number is odd or even. When I initially hit upon the problem, my immediate thought was to use the modulus function % and inspect the result.

However, a quick look at the PHP Manual showed a much easier way of determining whether a number is odd or even:

PHP:
  1. $status = (1 & $number) ? 'Odd' : 'Even';

The '&' sign represents the bitwise 'AND' operator, and the appropriate user comment explains:

The reason the bitwise AND ("&") operator works to determine whether a number is odd or even is because odd numbers expressed in binary always have the rightmost (2^0) bit = 1 and even numbers always have the 2^0 bit = 0.

4 comments July 13th, 2006


Calendar

July 2006
M T W T F S S
« Jun   Aug »
 12
3456789
10111213141516
17181920212223
24252627282930
31  

Posts by Month

Posts by Category