Home > Mobile >  what does "if(( number >> 1) <<1==number)" mean?
what does "if(( number >> 1) <<1==number)" mean?

Time:08-25

c program to check odd or even without using modulus operator

We can check a number is even or odd without using modulus and division operator in c program The another method is using shift operators number >> 1) <<1==number then it is even number,can someone explaain this?

CodePudding user response:

A right shift by x is essentially a truncating division by 2x.

A left shift by x is essentially a multiplication by 2x.

6 ⇒ 3 ⇒ 6
7 ⇒ 3 ⇒ 6

If this produces the original number, it's even.

CodePudding user response:

Right-shifting by one shifts off the low bit, left-shifting back restores the value without that low bit.

All odd numbers end in a low bit of 1, which this removes, so the equality comparison only returns true for even numbers, where the removal and re-adding of the low 0 bit does not change the value.

CodePudding user response:

A number is odd if its lowest (1) bit is 1. What this does is shift right by 1, and then right by one, effictively zeroing out this first bit. If that bit was already a 0 (i.e. the number is even), then the number doesn't change and the == passes. If it was a 1 then its now a zero and the equality check fails.

A better, more obvious implementation of this logic would be:

if(number & 0x1 == 0)

which checks directly whether the bit is a 0 (i.e. the number is even)

CodePudding user response:

We can check a number is even or odd without using modulus and division operator in c program The another method is using shift operators number >> 1) <<1==number then it is even number

Do not use if(( number >> 1) <<1==number) as it risks implementation defined behavior when number < 0.

Only for the pedantic

This is likely incorrect on rare machines that use ones' complement int encoding.

Of course such beast are so rare these days and the next version of C, C2x, is expected to no longer support non-2's complement encoding.

Alternative

Instead code can use:

is_odd = number & 1LLU;

This will convert various possible integer types of number into unsigned long long and then perform a simple mask of the least significant bit (the one's place). Even with negatives values in any encoding will convert mathematically to an unsigned value with the same even-ness.

Modulus operator??

... using modulus and division operator ...

In C there is no operator defined as modulus. There is %, which results in the remainder.
See What's the difference between “mod” and “remainder”?.

  •  Tags:  
  • c
  • Related