Search code examples
algorithmroundingbitwise-operatorsbitshift

How to perform a bitwise round up to even numbers if odd?


How to perform a bitwise only (shifts,and,or,xor..) round up to even numbers if the number is odd (also for negative numbers)?

Example:

  • Input: 3; Output: 4
  • Input: 4; Output: 4
  • Input: 5; Output: 6
  • Input: 6; Output: 6
  • Input: -14; Output: -14
  • Input: -15; Output: -14

What I tried: This works so far, but it seems to be kinda redundant?

(((n + 1) >> 1) << 1)

Is there a shorter solution?


Solution

  • A solution is to add the least significant bit to the number :

    n+(n&1)
    

    If n is even, its LSB is 0, and the number is unchanged as expected.
    If n is odd, its LSB is 1 and n will be changed to the even number immediately above it.

    This is based on an arithmetic operations and will work, for either positive and negative numbers.

    It does not even rely on the fact that numbers are coded in two's complement. The only real assumption is that even numbers have a LSB at 0 and odd numbers a LSB at 1. If n is coded in an unusual way, this method should still work, provided this assumption is verified. For instance, with numbers coded in sign-absolute value or with excess code (with the excess even).

    Your method, while correct on most computers, realizes ((n+1)÷2)×2 by means of right and left shifts. But the C or C++ standards leave (for the moment) implementation dependent the meaning of right shifts on signed integers and your code may break for negative numbers on some unusual architectures/compilers.