I have an assignment that asks to perform a number of functions using only these operators:
! ~ and ^ | + <→
In some problems it is useful to make some kind of integer x, becoming all 1s if it contains any 1s, but 0 will remain if it is 0. The reason I do this is that I can return y or z as follows :
// One of the two conditional values is now 0
int conditionalA = mask&y;
int conditionalB = ~mask&z;
// One of the values is combined with 0 using |
int out = conditionalA|conditionalB;
return out;
where I made the mask as follows:
// Make any x other than 0 all 1s
int mask = x;
mask |= mask>>1;
mask |= mask>>2;
mask |= mask>>4;
mask |= mask>>8;
mask |= mask>>16;
mask |= mask<<1;
mask |= mask<<2;
mask |= mask<<4;
mask |= mask<<8;
mask |= mask<<16;
There should be a better way to mask all 1 or 0, but I can't come up with a more efficient solution. Again, it is important that 0 remain 0 if x is 0.
Change . If statements are not parameters
source
share