From the given number, set the value of var to -1 if it is negative, and 1 if it is positive (without using if)

I often need such a function, for example, to understand the direction of touches on the iPhone and the only way to solve this problem using logic, for example:

int dir,distY;
distY = newY-oldY;

if (distY > 0) 
{
    dir = 1;
}
else if (distY < 0) 
{
    dir = -1;
}

I would like to know if there is a way to do this in one of mybey games using the math method or the old school way.

Clarification, a similar example of what I'm looking for:

i = ++i % max;

instead:

i++;
if ( i > max ) { i = 0; }
+3
source share
8 answers

, - C ++, true 1 false 0, : direction = (distY > 0) - (distY < 0);. , , distY=0 - 0 ( , ).

, , - , , , , . OTOH, , , .

+2

, , :

dir = distY / abs(distY);

, -, - ( C/++):

dir = distY >= 0 ? 1 : -1;

dir 1, distY .

+2

direction = distY/abs (distY)

, , distY 0.

+1

, signum. / , : if/else , .

:
sign (n) =
| -1, n < 0
| 0, n = 0 | 1, n > 0

, , ( ). - ( ), , , ​​ , +, .

+1

, ,

(i>0)?1:((i<0)?-1:0)

(, ).

, , , , .

if-else.

0

, 0 - false, 1 - true ( ), :

i = abs(distY) == distY; // 0 or 1
i = i*2 - 1; // -1 or 1
0

, , - C, Perl .

<=> :

$dir = $distY <=> 0;

(perldoc perlop):

"<=>" -1, 0 1 , , .

, , - - C, ++ / Objective-C.

0

, (), , 0 1 FALSE TRUE.

#:

    // Explanatory version:
    static int Sign(int val)
    {
        val = -(int)((uint)val >> 31); // int is 32 bit, so shift by n - 1.
        // uval now contains -1 for negative and 0 for positive.
        return val * 2 + 1;
        // -1 * 2 + 1 = -1
        //  0 * 2 + 1 = +1
    }

    // Terse form:
    static int Sign(int val)
    {
        return 1 - (int)((uint)val >> 31) * 2;
    }

, (, x86/x64). "1" (. ).

  • . , ( .Net).
  • AND 0x80000000. , , . - , ( ROL ROR, ).
  • We shift the value to the right by 31 bits. The shift operator will “destroy” any bits that “fall” from the end, so we are left with either 1 or 0 from the left to the bit 2^0. This means that if the value is negative, the value will be 1, and if it will be positive, it will be 0.
  • We return it back to int and then use simple math to map 0 and 1 to 1 and -1, respectively.

If you are targeting a big-endian, I think just changing the shift should give the right result.

0
source

Source: https://habr.com/ru/post/1753095/


All Articles