I’d like to get the sign of a float value as an int value of -1 or 1.
Avoiding conditionals is always a good idea in reducing computational cost. For instance, one way I can think of would be to use a fast bit-shift to get the sign:
float a = ...;
int sign = a >> 31; //0 for pos, 1 for neg
sign = ~sign; //1 for pos, 0 for neg
sign = sign << 1; //2 for pos, 0 for neg
sign -= 1; //-1 for pos, 1 for neg -- perfect.
Or more concisely:
int sign = (~(a >> 31) << 1) - 1;
- Does this seem like a good approach?
- Will this work for all platforms, given endianness concerns (as MSB holds sign)?
Any reasons why you don’t simply use:
Additionally most Number implementations have a signum method taking a primitive of that type and returning an int, so you can avoid casting for extra performance.
It will return +1 / 0 / -1 and it has been optimized to deliver a good performance.
For reference, you can have a look at the implementation in openJDK. The relevant bits are: