sgn / sign / signum function suggestions

It's not uncommon to need to know the arithmetic sign of a value, typically represented as -1 for values < 0, +1 for values > 0, or 0. Arduino provides the abs() function which strips the sign, returning a positive value, but no function specific for getting the sign.

A thread in the old forum provides some clever optimizations of such a function, but they all suffered a bit from readability and not being built-in.

Without concern for performance (not tested; don't care), I've been using the built-in constrain as follows:

int signOfX = constrain(x, -1, 1);

For me, this provides good-enough readability without having to define a separate function. This should work for any signed integer value (e.g., long) where x < -1 and x > 1 can be computed. (Constrain is not really a function but a compiler definition in Arduino.h.)

Posting this because searching for sign or signum in Arduino documentation currently returns only the more clever/more complicated discussion. Hope it's useful.

P.S., if you don't mind defining something, consider adding this near the top of your .ino file:

#define sgn(x) ((x) < 0 ? -1 : ((x) > 0 ? 1 : 0))

This follows the example of similar "functions" in Arduino.h and allows you to simply write int signOfX = sgn(x); and should work find for floating-point values, too.

Other possibilities discussed here.

Branchless, type-safe C++ version:

template <typename T> int sgn(T val) {
    return (T(0) < val) - (val < T(0));
}

Posting this because searching for sign or signum in Arduino documentation currently returns only the more clever/more complicated discussion

Why restrict yourself to searching Arduino documentation when the Arduino runs C++ ?

The closest built-in function I found was signbit():
http://www.cplusplus.com/reference/cmath/signbit/

Try this:

int signOfX = (x > 0) - (x < 0);

I got that from here: bit manipulation - sign function in C using bit operators only - Stack Overflow

It's interesting that all the examples in this thread store the one bit value in an int. What does it take to get people to use the proper type everywhere?

PaulS:
It's interesting that all the examples in this thread store the one bit value in an int. What does it take to get people to use the proper type everywhere?

Well, then, tell us the proper type.

odometer:
Well, then, tell us the proper type.

I think that that is pretty obvious. The smallest data type possible. In the case of a variable to hold one bit of data, the smallest type that can be used on the Arduino is 8 bits, so any signed 8 bit type can be used, such as int8_t or char (which is signed, for some strange reason).