簡體   English   中英

是否可以將 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?

我已經實現了以下代碼:

#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 )應該對此抱怨。

吉爾斯是對的​​。

要么使用std::cout <<我認為應該以正確的方式處理它,或者使用printf("i64value2 : [%lld]\\n",i64value2); 而打印應該解決它。

x86-64 ABI 下- long longlong相同,即 64 位值。 在這種情況下沒有精度損失。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM