Effectively make an int that has 1 all 1 but one that remains 0. 0

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

+5
source share
3 answers

Assuming 2 additions:

int mask = !x + ~0;

! 0 0 1, ~0 (-1), -1 0 .

+6

:

x = (x | -x) >> 31; // Note this is implementation specific.

, -, , . .

+3

Here's a worker, I think (assumes two arithmetic additions):

x = ~!!x + 1;

How did I get there?

Firstly, it !!xturns any nonzero fraction into 1, and 0 remains 0. Then, using 2 the complement equivalence for negation -x = ~x + 1, it’s great!

+2
source

All Articles