0

How the bitwise operator 'and' checks the number even or odd ???

can anyone explain this with programming language please ??

19th May 2020, 3:39 AM
Ahmed Muhammed
Ahmed Muhammed - avatar
1 Antwort
+ 4
Use 1 as a mask this will flip all bits except the ones place to 0. The result will only be 1 if the ones place is one which only occurs for odd numbers. Therefore, if the result is 0 the number is even, of the result is 1 the number is odd. This is also much faster than using the modulo operator as in (num % 2 == 0) if(num & 1 == 0) // number is even 10 = 00001010 1 = 00000001 & 00000000 if(num & 1 == 1) // number is odd 15 = 00001101 1 = 00000001 & 00000001
19th May 2020, 4:07 AM
ChaoticDawg
ChaoticDawg - avatar