Bitwise operations equivalent of greater than operator

后端 未结 8 1612
花落未央
花落未央 2020-12-05 10:30

I am working on a function that will essentially see which of two ints is larger. The parameters that are passed are 2 32-bit ints. The trick is the only operat

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 10:53

    EDIT:

    Okay, there were some issues with the code, but I revised it and the following works.

    This auxiliary function compares the numbers' n'th significant digit:

    int compare ( int a, int b, int n )
    {
        int digit = (0x1 << n-1);
        if ( (a & digit) && (b & digit) )
           return 0; //the digit is the same
    
        if ( (a & digit) && !(b & digit) )
           return 1; //a is greater than b
    
        if ( !(a & digit) && (b & digit) )
           return -1; //b is greater than a
    }
    

    The following should recursively return the larger number:

    int larger ( int a, int b )
    {
        for ( int i = 8*sizeof(a) - 1 ; i >= 0 ; i-- )
        {
           if ( int k = compare ( a, b, i ) )
           {
               return (k == 1) ? a : b;
           }
        }
        return 0; //equal
    }
    

提交回复
热议问题