Asked • 06/19/19

Fastest way to get sign in Java?

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; 1. Does this seem like a good approach? 2. Will this work for all platforms, given endianness concerns (as MSB holds sign)?

1 Expert Answer


Chandra P. answered • 08/28/19

4.9 (20)

Experienced and Qualified Engineer Specializing in Java

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.


Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.