How to determine if a number is positive, negative, or zero without using if or for?

I want to implement the sign and flag of zero in a microprocessor. Therefore, I need to write a function to determine if a number is positive, negative, or zero without using if or for loops, and only logical and bitwise operators are allowed . I did the following. But how to implement it for the condition zero ?

 int status (int x) { int sign = (x >> 31); return sign; } 

Any suggestions?

+6
source share
3 answers

Return -1 for negative values โ€‹โ€‹of 0 for zero, 1 for positive values โ€‹โ€‹of x .

 int status (int x) { int sign = (x > 0) - (x < 0); return sign; } 
+7
source

Is this enough for your purpose?

 int status(int val) { int minus = (val&0x80000000)&&TRUE; int pos = (val&0x7FFFFFFF)&&(!(val&0x80000000)); int r = 0 - minus + pos; return r; } 
+2
source

try it

 int status (unsigned no) { int sign = 0; // If Zero // If -Ve = -1 OR If +Ve = -2 (sign = ( no | 0 )) && ( sign = (~( ( (no << 1) >> 1 ) == no)) ); // If +Ve (sign == -2) && (sign = 1); return sign; } 
0
source

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


All Articles