Re: Is it odd or even??? Optimize!!!
| From: | Julian Wood | Date: | Mon, 05 Mar 2001 22:42:18 +0000 |
| Subject: | Re: Is it odd or even??? Optimize!!! | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-42675@lists.php.net to get a copy of this message | ||
Clever. For those of us unfamiliar with bitwise ops, here's how this works:
The bitwise and op (&) works on bits like this:
dig1 dig2 Result
0 0 0
0 1 0
1 0 0
1 1 1
An even number's binary representation always ends with 0 (ie 12 = 1100)
while an odd ends with 1 (ie 13 = 1101).
So doing a bitwise & with 1 will only produce 1 if the last binary digit is
1 (ie an odd num), otherwise 0 (see table).
And, like Nathan implies, this will be very fast (way faster than modulus),
since you only ever deal with 2 bits of info.
For an explanation of other bitwise operators, look here:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/bitwise.html
J
on 3/5/01 12:36 PM, Nathan Cassano at nathan@cjhunter.com wrote:
>
> You all are a bunch of un-optimizing novices. Just do some bit banging.
>
> i.e.
>
> if(1 & number){
> echo "$number is odd";
> }else{
> echo "$number is even";
> }
>
>
> -----Original Message-----
> From: Brandon Orther [mailto:brandon@webintellects.com]
> Sent: Monday, March 05, 2001 12:18 PM
> To: PHP User Group
> Subject: [PHP] Is it odd or even???
>
>
> Hello,
>
> Is there an easy way to check and see if a number is odd or even?
>
> Thank you,
>
> --------------------------------------------
> Brandon Orther
> WebIntellects Design/Development Manager
> brandon@webintellects.com
> 800-994-6364
> www.webintellects.com
> --------------------------------------------
>