简体   繁体   中英

Casting from uint64_t to double results in incorrect values

When casting from a large uint64_t value to a double . The results are not as expected. Why is this, and is there a way to solve it. I'm using gcc 8.3.0

int main
{
   uint64_t var64 = 844421103279395000;

   printf("var64     = %llu\n", var64 );

   double varDouble = (double)var64;

   printf("varDouble = %lf\n", varDouble );

   return 0;
}

The output is as follows:

var64     = 844421103279395000
varDouble = 844421103279394940.000000

A double , assuming it uses IEE754 double-precision representation, can only hold 53 bits of precision. A uint64_t uses all 64 bits as value bits, meaning that there are some values that can be stored exactly in a uint64_t that cannot be stored exactly in a double .

In your example, 844421103279395000 has a hex representation of 0BB7 FC84 FDCF D0B8 . The closest value with 53 bits of precision is 0BB7 FC84 FDCF D080 which is 844421103279394944 in decimal. This value is close to what is being displayed, with the difference probably due to how printf handles writing significant digits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM