code_junkie

Simplest way to check if two integers have same sign?

Nov 10th, 2011
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. bool SameSign(int x, int y)
  2. {
  3. return (x >= 0) ^ (y < 0);
  4. }
  5.  
  6. template <typename valueType>
  7. bool SameSign(typename valueType x, typename valueType y)
  8. {
  9. return (x >= 0) ^ (y < 0);
  10. }
  11.  
  12. return ((x<0) ==(y<0));
  13.  
  14. bool same = ((x ^ y) & >> 31) != 1;
  15.  
  16. bool same = !((x ^ y) & >> 31);
  17.  
  18. inline bool same_sign(int x, int y) {
  19. return (x^y) >= 0;
  20. }
  21.  
  22. inline bool same_sign(int x, int y) {
  23. return (x<0) == (y<0);
  24. }
  25.  
  26. #define SIGNBIT (~((unsigned int)-1 >> 1))
  27. if ((x & SIGNBIT) == (y & SIGNBIT))
  28. // signs are the same
  29.  
  30. int mask = 1 << 31;
  31. (a & mask) ^ (b & mask) < 0;
  32.  
  33. bool compare(T left, T right)
  34. {
  35. return (left < 0) && (right < 0);
  36. }
  37.  
  38. int sameSign(int a, int b) {
  39. return ~(a^b) & (1<<(sizeof(int)*8-1));
  40. }
  41.  
  42. template <typename T> T sameSign(T a, T b) {
  43. return ~(a^b) & (1<<(sizeof(T)*8-1));
  44. }
Add Comment
Please, Sign In to add comment