Implementing logical right shift using only “~ & ^ | + << >> =” operators and 20 operations

后端 未结 2 1841
误落风尘
误落风尘 2020-12-19 09:31

So I have an assignment that I have to code a function in c that uses only the bitwise operations of ~ , & , ^ , | , + , << , >> , and =. I have to use only 20 ope

2条回答
  •  悲哀的现实
    2020-12-19 09:42

    The difference between logical and arithmetic shift are the bits shifted in from the left. To implement logical shift in terms of arithmetic you can do the arithmetic shift and then clear the new bits. In pseudo-code:

    1. Generate a mask that will clear the leftmost n bits when ANDed with the result.
    2. Shift right by n bits.
    3. AND the mask.

    Using AND means you don't have to care what bits are shifted in. You just want to unconditionally set them to 0.

    The question then is how to generate the mask. I'll leave that as an exercise for you.

提交回复
热议问题