Advertisement
Guest User

Michael

a guest
Sep 28th, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. /*
  2. gcc test.c -o test -O2 -Wall -Werror -pipe -std=c11
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <stdint.h>
  7. #include <limits.h>
  8.  
  9. void
  10. swap(int32_t v1, int32_t v2)
  11. {
  12. v1 ^= v2;
  13. v2 ^= v1;
  14. v1 ^= v2;
  15. }
  16.  
  17. int32_t
  18. satsum(int32_t v1, int32_t v2)
  19. {
  20. int32_t res;
  21. __builtin_sadd_overflow(v1, v2, &res);
  22. if(v1 >= 0 && v2 >= 0) {
  23. if(res < 0) {
  24. if(v1 < v2) {
  25. swap(v1, v2);
  26. }
  27. int32_t dif = v1 - v2;
  28. res = (res + dif) / 2 + 1;
  29. v1 -= res;
  30. return v1;
  31. } else {
  32. return res;
  33. }
  34. } else if(v1 < 0 && v2 < 0) {
  35. if(res >= 0) {
  36. if(v1 > v2) {
  37. swap(v1, v2);
  38. }
  39. int32_t dif = v2 - v1;
  40. res = (res - dif) / 2;
  41. v1 -= res;
  42. return v1;
  43. } else {
  44. return res;
  45. }
  46. } else {
  47. return res;
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement