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