Thread: Checking for an even\odd number by using bitshifting?

1. Member
Join Date
Jun 2013
Posts
12
Rep Power
0

Checking for an even\odd number by using bitshifting?

Is there any way to do this?

2. Senior Member
Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
14

Re: Checking for an even\odd number by using bitshifting?

You don't need to shift bits but you can test them. Just check to see if the low order bit is set or not. If it is set, the number is odd, if it is not set, the number is even.

Java Code:
```int value = 23;
if ((value & 1) == 1) {
System.println(value + " is odd\n");
} else
System.println(value + " is even\n");
}```
Regards,
Jim

3. Member
Join Date
Jan 2013
Location
Texas
Posts
45
Rep Power
0

Re: Checking for an even\odd number by using bitshifting?

Originally Posted by jamgor
Is there any way to do this?
You can use the modulus operator % which so when a number is divided by 2 if the remainder is 0 then it is an even number, else it is an odd number.
Java Code:
``` if ((24 % 2) == 0)  // % is modulus operator
print out 24 is even
else
print out 24 is not even```

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•