logo CodeStepByStep logo

swapEvenOddBits

Language/Type: C++ bit algorithms

Write a function named swapEvenOddBits that accepts as a parameter an integer n and returns an integer whose binary representation is equal to n's if the values at alternating bit positions are swapped. For example, if the call is swapEvenOddBits(44), the binary representation of 43 is 101011 preceded by 26 zeros, so you should return the number whose binary representation is 010111, which is 23.

The challenge here comes from the constraints on the problem. You should solve this problem using bitwise operators and arithmetic. Do not use any collections or strings to solve the problem. Also, do not use any loops. You may assume that an int occupies 32 bits in memory and is encoded using ones' complement.

Function: Write a C++ function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.