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.
 
 
 
 

42 lines
1.1 KiB

  1. #include "scan.h"
  2. static const unsigned long maxlong = ((unsigned long)-1)>>1;
  3. #ifdef UNITTEST
  4. #undef UNITTEST
  5. #include "scan_ulonglong.c"
  6. #define UNITTEST
  7. #endif
  8. size_t scan_longlong(const char* src,signed long long* dest) {
  9. size_t i,o;
  10. unsigned long long l;
  11. char c=src[0];
  12. unsigned int neg=c=='-';
  13. o=c=='-' || c=='+';
  14. if ((i=scan_ulonglong(src+o,&l))) {
  15. if (i>0 && l>maxlong+neg) {
  16. l/=10;
  17. --i;
  18. }
  19. if (i+o) *dest=(signed long long)(c=='-'?-l:l);
  20. return i+o;
  21. } return 0;
  22. }
  23. #ifdef UNITTEST
  24. #include <assert.h>
  25. int main() {
  26. long long i;
  27. assert(scan_longlong("1234",&i)==4 && i==1234);
  28. assert(scan_longlong("-1234",&i)==5 && i==-1234);
  29. assert(scan_longlong("+1234",&i)==5 && i==1234);
  30. assert(scan_longlong("2147483647",&i)==10 && i==2147483647); // INT_MAX
  31. assert(scan_longlong("-2147483648",&i)==11 && i==-2147483648); // INT_MIN
  32. assert(scan_longlong("9223372036854775807",&i)==19 && i==0x7fffffffffffffffull); // LONG_MAX
  33. assert(scan_longlong("-9223372036854775808",&i)==20 && i==(long long)0x8000000000000000ull); // LONG_MIN
  34. return 0;
  35. }
  36. #endif