English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I know you could just use if statements but there's probably a better way to make sure a integer variable is even, and if its odd, it adds one to make it even.

2007-07-11 05:41:07 · 2 answers · asked by uk 2 in Computers & Internet Programming & Design

2 answers

This will do it:

(x + 1) &~1

~1 is the binary complement of 1 (an int with 0 in the 1's position, and 1 in every other bit).

& bitwise and with (~1) will clear the 1s bit of the integer but otherwise leave it unchanged.

If you do just "x & ~1", then you'll round down (any even number already has 0 in the 1s bit and is unaffected, any odd number loses 1 in its 1s bit and is decreased by one: 37 -> 36)

If you want odd numbers rounded up, add one first (an odd number will become the next even number, an even number will just get a '1' in its 1s bit which will then be cleared).

===============
Note, though, that while this is very short, it is not the most readable way to write this. If you really want to say "increment all odd numbers" you should use an if statement:

if (x & 1) ++x;

Elegance in terms of the shortest expression, isn't always the most maintainable or readable way to do things.

2007-07-11 06:19:47 · answer #1 · answered by McFate 7 · 0 0

The way I did this was to take my variable and see by dividing it by 2 if it has a reminder. If so then I knew it was Odd otherwise it was even. You still have to use one IF for my check variable for whether it was Odd or Even.

2007-07-11 05:47:15 · answer #2 · answered by Anonymous · 0 0

fedest.com, questions and answers