简体   繁体   English

如何仅使用按位运算符来防止C中的位溢出

[英]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. 我必须重写一种方法,以仅使用按位运算符而不使用条件语句来找出x是否小于或等于y。 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. 假设我们知道int是4字节2的补充。

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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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