How do you transform a number to its sign (for example -50 = -1, 50 = 1) without using the if statement, just mathematical operations?
Asked
Active
Viewed 60 times
-6
-
no sign bit to look? – huseyin tugrul buyukisik Feb 11 '17 at 00:44
-
1Possible duplicate of [Is there a standard sign function (signum, sgn) in C/C++?](http://stackoverflow.com/questions/1903954/is-there-a-standard-sign-function-signum-sgn-in-c-c) – J... Feb 11 '17 at 00:46
-
Untested, but have you tried `1 | (n & (1 << (sizeof(n) * 8) - 1))`? I'll leave it up to you to figure out what all of that does. – Qix - MONICA WAS MISTREATED Feb 11 '17 at 00:46
-
Why so many downvotes? Too easy to answer? – gigi Feb 11 '17 at 00:50
-
It's usually simplest just to test it: `(x < 0) ? -1 : (x > 0) ? +1 : 0;`. Improving on that is hard — unless you can get at the flags from an assembler comparison so you only do one comparison, not two. If the value is non-zero, `x / abs(x)` gives you the right answer, but it costs a division plus the absolute-value operation. – Jonathan Leffler Feb 11 '17 at 00:50
-
@huseyintugrulbuyukisik I'd like to know your answer using the sign bit – gigi Feb 11 '17 at 00:52
-
@gigi compare your number to positive zero implementation defined – huseyin tugrul buyukisik Feb 11 '17 at 00:54
-
I just found the perfect answer : (x > 0) - (x < 0) it uses a condition but not an "if" so I guess it's ok – gigi Feb 11 '17 at 00:55
-
2@gigi My guess is because it's a trivial mathematical problem so dear to universities yet unrelated to C++. It brings very little to the (C++) table. – Feb 11 '17 at 00:55
-
@gigi `(x > 0) - (x < 0)` has no branching conditions - the `>` and `<` are operators which return a numerical value. – J... Feb 11 '17 at 02:34
1 Answers
2
Why not just do this
int sign = i<=0 ? -1 : 1;

Ed Heal
- 59,252
- 17
- 87
- 127
-
1Why not? It has a branch... see (from the dupe) : http://stackoverflow.com/a/1903975/327083 – J... Feb 11 '17 at 00:49
-
1Nothing in *this* question mentioned a branch, just that it shouldn't use an `if` statement :-) This answer is wrong for a totally *different* reason: zero is *not* negative. – paxdiablo Feb 11 '17 at 01:00
-
1Thank you - my answer does not have an if in it. In fact it does not have a f but has an i - sorry for the use of a vowel – Ed Heal Feb 11 '17 at 01:01