I have a code in which I am passing string "5368709120" to function strtoull() and it should had returned me number 5368709120 but instead it returns me 1073741824 which is incorrect.
What may be the possible cause of this and how to rectify it?
typedef unsigned long long ULL_Type;
char *numStr = "5368709120";
ULL_Type num;
num = strtoull(numStr, NULL, 10);
Show us the code you used to determine that the value stored in num is 1073741824 rather than 5368709120! Decimal 5368709120 is hexadecimal 0x140000000 and decimal 1073741824 is 0x40000000. So, Jim's guess that you printed the value of num using something like:
printf("%lu\n", num);
sure seems to fit the symptoms of what you have described.
Please change:
num = strtoull(numStr, NULL, 10);
in your code to:
num = strtoull(numStr, NULL, 10);
printf("%llu\n", num);
Check the return value from strtoull...it is better not to assume anything and make sure to include <stdlib.h> header file wherein strtoull is declared and post the entire code if it aint too big...
There's something goofy in your program so post it here so others can look at it...as the max value of ULL "18446744073709551615" is way bigger than "5368709120" so im not sure how you are getting wrong results...
If you had posted a complete yet minimal, compilable program which reproduces the issue, it is likely that this thread would have been resolved long ago.
Regards,
Alister
---------- Post updated at 03:19 PM ---------- Previous update was at 02:54 PM ----------
jim_mcnamara and don_cragun in posts #2 and #4, respectively, correctly deduced from the nature of the numbers involved that a long long was left-truncated into an integer. However, their responses were handicapped by not having access to a complete program.
Had your original post been more forthcoming, either of them would have seen immediately that the truncation was not caused by a printf bug but by incomplete headers.
You need to include the correct headers so that the compiler doesn't default to implicit function prototypes which treat arguments and return values as integers.
What you are seeing is the result of strtoull's return value taken as an integer before assignment to intValue (as if there were a cast operation there). There are surely other bugs just waiting to bite.
Consult the manual pages of each library function to learn which headers must be included.
Also, you should enable compiler warnings; they would have pointed this out to you.