bool fits16(int x) { short y = x; return y == x; }
Just kidding :) Here is the real answer, assuming int is 32 bits and short is 16 bits and two representations:
Edit: see the latest change for the correct answer!
bool fits16(int x) { int y = x & 0xffff0000; if (x & 0x00008000) { return y == 0xffff0000; } else { return y == 0; } }
Without statements that should do this:
return ( !(!(x & 0xffff0000) || !(x & 0x00008000)) || !((x & 0xffff0000) || (x & 0x00008000)) );
Edit: Oli is correct. For some reason I thought they were allowed. Here's the last attempt with an explanation:
We need the 17 most significant bits of x be either all or all zeros. So let's start by masking the other bits:
int a = x & 0xffff8000; // we need a to be either 0xffff8000 or 0x00000000 int b = a + 0x00008000; // if a == 0xffff8000 then b is now 0x00000000 // if a == 0x00000000 then b is now 0x00008000 // in any other case b has a different value int c = b & 0xffff7fff; // all zeroes if it fits, something else if it doesn't return c;
Or more briefly:
return ((x & 0xffff8000) + 0x8000) & 0xffff7fff;
cyco130
source share