c++ - 是否可以将 long long 返回值分配给 int64_t 而不会丢失 64 位机器的精度?

标签 c++ c

我已经实现了以下代码:

#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_tlong long 应该是等价的类型。还有一些地方提到要使用int64_t 而不是long long。 但是当我查看 stdint.h 时,它告诉我为什么会看到上述行为:

# if __WORDSIZE == 64 
typedef long int  int64_t; 
# else 
__extension__ 
typedef long long int  int64_t; 
# endif 

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

我的问题是,是否有一种解决方法/解决方案可以将 long long 返回值分配给 int64_t 而不会丢失 64 位机器中的精度?

提前致谢

最佳答案

损失不会发生在转换中,而是发生在打印中:

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

int64_t 参数的访问就像是 int 一样。这是未定义的行为,但通常低 32 位是符​​号扩展。

正确的编译器警告(例如 gcc -Wformat)应该对此进行提示。

关于c++ - 是否可以将 long long 返回值分配给 int64_t 而不会丢失 64 位机器的精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11862622/

相关文章:

c++ - 如何在 C++ 中过滤掉未触及的代码

c++ - 如何在 mfc CListCtrl 中实现简单的复制/粘贴功能?

c - 结构赋值给出 "expected an expression"

c - 二进制浮点加法

c++ - 统一影响着色器流程和性能

c++ - 为什么我的运算符重载不编译?

c++ - 我想知道当函数在其中创建对象时会发生什么

无法通过双击运行 SDL2 可执行文件

c - 为什么我不能将初始化列表括在括号中?

c++ - FORTRAN 中的 DIMENSION 语句