Odd and even numbers (using & or%)

I always used the following to find even and odd numbers:

if( $num % 2 ) { echo "odd"; } if( !($num % 2) ) { echo "even"; } 

But recently, I came across the following code, which works exactly the same:

 if( $num & 1 ) { echo "odd"; } if( !($num & 1) ) { echo "even; } 

What is the logic & in the second method?

I went to check PHP: Arithmetic operators , and the ampersand is not part of these options.

Thanks.

+4
source share
2 answers

This is the bitwise-AND operator. Remember that on a computer, every integer is stored in binary form, and the binary digit with the least significance is 2 ^ 0 == 1. So, every odd number will have a lower binary digit = 1.

So, the bitwise AND operator compares your bit value with constant 1 . Bits that are 1 in both operands are set to 1 as a result, but bits that are 0 in both operands are set to 0 as a result. The end result (which will be either 1 or 0 ) is forced to boolean due to PHP because you use it as a clause in the if() .

There is a very good reason to check for uniformity with & instead of % : Speed! The % operator requires a division operation, so the remainder can be calculated, which is computationally large, much more expensive than just comparing the bits directly.

Example:

 $num = 9; // 9 == 8 + 1 == 2^3 + 2^0 == 1001b echo (string)($num & 1); // 1001b & 0001b = 0001b - prints '1' $num = 10; // 10 == 8 + 2 == 2^3 + 2^1 == 1010b echo (string)($num & 1); // 1010b & 0001b = 0000b - prints '0' 
+10
source

& is binary AND .

The binary value of the odd number AND 1 will be 1, and the binary value of the even number AND 1 will be 0.

This is because the binary value of an odd number always ends with 1, and the binary value of an even number ends with 0. So ...

10101101 & 00000001 = 00000001 in case of an odd number and

10101100 & 00000000 = 00000000 in the case of an even number.

+6
source

Source: https://habr.com/ru/post/1486892/


All Articles