Reputation: 1868
Am I doing anything wrong in this following program?
Code
#include <stdio.h>
int main()
{
long x=1290323123123;
int len = snprintf(NULL,0, "%ld", x);
printf("%ld %ld",x,len);
return 0;
}
Output: 1832934323 10
Upvotes: 1
Views: 114
Reputation: 523314
1290323123123 requires 41 bits to store, but that long
probably is just 32-bit long, so the extra 9 bits are gone.
1290323123123 = 0x12c6d405bb3
^^^
excessive data that is chopped off
= 0x6d405bb3
= 1832934323
Use
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
int main () {
int64_t x = 1290323123123LL;
// ^^^^^^^ ^^
int len = snprintf(NULL, 0, "%"PRId64, x);
// ^^^^^^^
printf("%"PRId64" %d\n", x, len);
// ^^^^^^^^
return 0;
}
to make sure the type is at least 64-bit long, so it can store that value completely (result: http://www.ideone.com/BnTjJ).
Upvotes: 6
Reputation: 1694
Your 'long' type can only hold 4 bytes. The value you've assigned 'x' is greater than 4 bytes.
Hex(1290323123123) = 12C 6D40 5BB3 Hex(1832934323 ) = 6D40 5BB3
So the number it's outputting is the same as the lower 4 bytes of the number you're trying to print.
Some compilers may have larger 'long' types - prior to C99 and the introduction of types like int64_t
I don't think there is one standard for (name, size) pairs.
Upvotes: 2