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
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:
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.
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.