简体   繁体   中英

how to guard against bit overflow in C using only bitwise operators

I have to re-write a method to find out if x is less than or equal to y using only bitwise operators and no conditional statements. I have this so far:

int isLessOrEqual(int x, int y)
{
    int a = x + (~y) + 1;
    return ((a&0x80000000) >> 31);
}

But I have no idea how to guard against overflow? Can anyone lend a helping hand?

[Edit] Bad solution as it uses conditionals. I'll leave it up for a while for as it may provide insight.

Assume we know int is 4-byte 2's compliment.

if (x == y) return 1;
int SignMask = 0x80000000;
// if x & y have different signs ...
if ((x & SignMask) != (y & SignMask)) {
  return !!(x & SignMask);  
}
// Continue with your original code knowing overflow will not happen.

Just for the sake of exercise, The following twisted code will do without any "+" or conditional statements (unless you consider cast to boolean conditional).

#define MSB 0x80000000
typedef bool (*RecurseFunc)(unsigned int, unsigned int);

bool EndRecursion(unsigned int ux, unsigned int uy)
{
    // stop recursion - ux cannot be smaller than uy
    return false;
}

bool CompareMSB(unsigned int ux, unsigned int uy)
{
    // jump table, may make global...
    RecurseFunc Handler[2] = {EndRecursion, CompareMSB}; 

    // yMsbBigger == MSB only iff Y"MSB==1 and X:MSB==0
    unsigned int yMsbBigger = ((~ux) & uy) & MSB; 
    // differentMsb will be MSB only iff the MSB of Y different MSB of x
    unsigned int differentMsb = (uy ^ ux) & MSB; 

    // prepare to check on the next bit - shift it to MSB position
    ux <<= 1;
    uy <<= 1;

    // we may want to check the remaining bits if ux,uy had same signs and 
    //     the remaining bits of y are not all 0
    bool mayRecurse = ((bool)uy) && (!(bool)differentMsb); 

    // C will not evaluate the second expression if the first is true
    // the second expression will "EndRecursion" if we may not recurse - 
    //     otherwise recurse
    return (((bool)yMsbBigger) || Handler[mayRecurse](ux, uy));
}

bool isYGreater(int x, int y)
{
    // we reverse the sign bits so positive value will have MSB=1, making it 
    //     "greater" then negative value's MSB
    unsigned int xbits = (unsigned int)x ^ MSB;
    unsigned int ybits = (unsigned int)y ^ MSB;

    return (CompareMSB(xbits, ybits));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM