c - How to compare two numbers to see which is greater -


Comparison of two numbers X, Y; If X> Y return back to 1, return the second. I only call it a bitwire operator such as >> & lt; & Lt; ~! & Amp; | ^ +

So far I found this:

  int greaterThan (int x, int y) {return (~ (x-y)> 31); }  

So if xy is negative, then the most important one will be 1. So I refuse to get it from 0 and move it so that it can return 0. If xy is positive, the most important bit would be 0. To get it 1 and bring it back to the crib 1. It does not seem to work. Am I doing this wrong or am missing something?

Your method does not work for many reasons:

  • Values ​​are signed values ​​on x and y , subtraction may be overflow. According to the C standard, not only is the result of undefined behavior , but generally in those applicable processes where the overflow is wrapped, it will give false results. For example, if x is INT_MIN and y is 1 , xy generated Will be INT_MAX , which does not have a high bit set.

  • If x and y are unsigned values, then x = UINT_MAX and Y = 0 is an example where you get an incorrect answer. You must apply a condition to the values ​​of x and y for the purpose of this examination (for example, its not a high bit is set). / P>

It comes down to the comparison of "high bits" to compare, you need a bit more than the number of bits in the values ​​being compared. . In assembly language on the appropriate-CISC-eye architecture, the layer flag provides this extra bit, and special conditional jump instruction (as well as instructions for taking / borrowing instructions) are able to read the value of the carry flag such that the Cary flag There is no way to reach, though an alternative approach may be to use a larger integer type (such as long time ) so that you can not Not be able to get an extra bit. Good collateral will actually translate the carrie flag to read rather than meet the major arithmetic functions.


Comments