Advertisement
Guest User

you would never write this in production...right?

a guest
Jan 18th, 2018
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.48 KB | None | 0 0
  1. int saturating_add(int u, int v)
  2. {
  3.     unsigned s = (unsigned)(u + v);
  4.        
  5.     // overflow test
  6.     unsigned q = s - u;  
  7.     unsigned p = q >> 31; // if this is 1, we have an overflow  
  8.    
  9.     // underflow test
  10.     unsigned p1 = (u >> 31) & (v >> 31); // if 1, they're both < 0
  11.     unsigned p2 = (p1 ^ (s >> 31)) & ((s >> 31) == 0); // if 1, we have an underflow
  12.  
  13.     return (int)((s & (0xFFFFFFFF + (p2 | p))) | (INT_MIN & (INT_MAX + p2)) | (INT_MAX & (INT_MIN - p)));  
  14. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement