是否可以将long long returne值分配给int64_t而不会在64位计算机上失去精度? [英] Is it possible to assign long long returne value to int64_t without losing the precision in a 64-bit Machine?

查看:50
本文介绍了是否可以将long long returne值分配给int64_t而不会在64位计算机上失去精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了以下代码:

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);
}

上述程序的输出是:

s : [10811535359]
i64value1 : [-2073366529]
llvalue : [10811535359]
i64value2 : [-2073366529]

使用的编译器是:

 gcc version 4.1.2 20080704 (Red Hat 4.1.2-48)

操作系统为 x86_64 GNU/Linux 2.6.18-194

因为 long long 是一个带符号的64位整数,并且在所有意图和目的上均与 int64_t 类型相同,因此在逻辑上 int64_t long long 应该是等效的类型.有些地方提到使用 int64_t 代替 long long .但是当我查看 stdint.h 时,它告诉我为什么看到上述行为:

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 

在64位编译中, int64_t long int ,而不是 long long int .

In a 64-bit compile, int64_t is long int, not a long long int.

我的问题是,是否有一种解决方法/解决方案,可以将长整型长返回值分配给int64_t,而不会损失64位计算机的精度?

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?

预先感谢

推荐答案

损失不是在转换中发生的,而是在印刷中发生的:

The loss does not happen in the conversions but in the printing:

printf("i64value1 : [%d]\n",i64value1);

int 一样访问 int64_t 参数.这是不确定的行为,但是通常低32位是符号扩展的.

The int64_t argument is accessed as if it were an int. This is undefined behaviour, but usually the low 32 bits are sign extended.

正确的编译器警告(例如gcc -Wformat )应该对此有所抱怨.

Proper compiler warnings (such as gcc -Wformat) should complain about this.

这篇关于是否可以将long long returne值分配给int64_t而不会在64位计算机上失去精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆