I have implemented below code :
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<cstdlib>
#include<sys/types.h>
main()
{
int64_t i64value1 = 0;
int64_t i64value2 = 0;
long long llvalue = 0;
const char *s = "10811535359";
i64value1 = atoll(s);
llvalue = atoll(s);
i64value2 = llvalue;
printf("s : [%s]\n",s);
printf("i64value1 : [%d]\n",i64value1);
printf("llvalue : [%lld]\n",llvalue);
printf("i64value2 : [%d]\n",i64value2);
}
Output of the above progrom is :
s : [10811535359]
i64value1 : [-2073366529]
llvalue : [10811535359]
i64value2 : [-2073366529]
The compiler used is :
gcc version 4.1.2 20080704 (Red Hat 4.1.2-48)
The OS is x86_64 GNU/Linux 2.6.18-194
Since long long is a signed 64-bit integer and is, for all intents and purposes, identical to int64_t type, logically int64_t and long long should be equivalent types. And some places mention to use int64_t instead of long long.
But when I look at stdint.h, it tells me why I see the above behavior:
# if __WORDSIZE == 64
typedef long int int64_t;
# else
__extension__
typedef long long int int64_t;
# endif
In a 64-bit compile, int64_t is long int, not a long long int.
My Question is, Is there a workaround/solution to assign long long returned value to int64_t without losing the precision in 64 bit Machine?
Thanks in advance
The loss does not happen in the conversions but in the printing:
The
int64_targument is accessed as if it were anint. This is undefined behaviour, but usually the low 32 bits are sign extended.Proper compiler warnings (such as gcc
-Wformat) should complain about this.