I would be wary of any bitwise tricks to determine the sign of integers, since then you should make assumptions about how these numbers are represented inside.
Almost 100% of the time, integers will be stored as two compliments , but it is not a good practice to make assumptions about internal components unless you use a data type that guarantees a specific storage format.
In two compliments, you can simply check the last (leftmost) bit in the integer to determine if it is negative, so you can only compare these two bits. This would mean that 0 would have the same sign as a positive number, but this contradicts the sign function implemented in most languages.
Personally, I just use the sign function of your chosen language. It is unlikely that there will be any performance issues with such calculations.
SpoonMeiser Sep 15 '08 at 21:06 2008-09-15 21:06
source share