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

后端 未结 2 1814
误落风尘
误落风尘 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.

    0 讨论(0)
  • 2020-12-19 10:09

    If the sign bit is not set, (x >> n) == (x >>> n). If the sign bit is set, we mask it off before doing the shift, then add it back: (x & 0x7FFFFFFF) >> n | (0x40000000 >> (n - 1)).

    If we know, which of the two cases we have, the computation becomes easier. If we could use if, we could combine the two cases. We have to emulate a conditional.

    int signBit1 = (x & 0x7FFFFFFF) >> n | (0x40000000 >> (n - 1));
    int signBit0 = x >> n;
    var signBitIsolated = x & 0x80000000; // either 0 or 0x80000000
    var signMask = signBitIsolated >> 31; //either 0 or 0xFFFFFFFF
    var combined = (signBit0 & ~signMask) | (signBit1 & signMask);
    return combined;
    

    We simulate a conditional by generating an all-zeros or all-ones mask, and or-ing the two cases.

    I think you said that the input domain is restricted to one byte. The same idea applies, but with different constants.

    0 讨论(0)
提交回复
热议问题