Mirror of :pserver:cvs@cvs.fefe.de:/cvs libowfat https://www.fefe.de/libowfat/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

50 lines
1015 B

  1. #if defined(__GNUC__) && (__GNUC__ >= 5)
  2. #include "uint64.h"
  3. int imult64( int64 a, int64 b, int64* c) { return !__builtin_mul_overflow(a,b,c); }
  4. #else
  5. #include "safemult.h"
  6. #if defined(__GNUC__) && (defined(__x86_64__) || defined(__ia64__) || defined(__powerpc64__) || defined(__alpha__) || defined(__mips64__) || defined(__sparc64__))
  7. int imult64(int64 a,int64 b,int64* c) {
  8. __int128_t x=((__int128_t)a)*b;
  9. if ((*c=(int64)x) != x) return 0;
  10. return 1;
  11. }
  12. #else
  13. int imult64(int64 a,int64 b,int64* c) {
  14. int neg=(a<0);
  15. uint64 d;
  16. if (neg) a=-a;
  17. if (b<0) { neg^=1; b=-b; }
  18. if (!umult64(a,b,&d)) return 0;
  19. if (d > 0x7fffffffffffffffULL + neg) return 0;
  20. *c=(neg?-d:d);
  21. return 1;
  22. }
  23. #endif
  24. #endif
  25. #ifdef UNITTEST
  26. #include <assert.h>
  27. int main() {
  28. int64 c;
  29. assert(imult64(0x4000000000000000ll,2,&c)==0);
  30. assert(imult64(-0x4000000000000000ll,2,&c)==1 && c==(int64)-0x8000000000000000ll);
  31. assert(imult64(0x3fffffffffffffffll,2,&c)==1 && c==0x7ffffffffffffffell);
  32. return 0;
  33. }
  34. #endif