简体   繁体   中英

How to convert bytes from uint64_t to double?

I have binary file from which I read uint64_t val (using little-endian). Now I want to convert this uint64_t to double (not just casting, but exactly the number that would be double if I entered it from the file). So the should has the same bit representation. How I should do this?

Simple portable way:

uint64_t u64 = read_from_file();
double d;
memcpy(&d, &u64, sizeof(d));

Most compilers will generate just a couple of instructions for this.

This is one way to do it:

uint64_t val = someCodeThatReadsTheValue();
auto valPtr = &val;
double dVal = *reinterpret_cast<double*>(valPtr);

As pointed out in the comments, this is Undefined Behaviour , although it will work in most compilers.

If you don't want to trust your compiler you can do the following.

uint64_t val1 = someCodeThatReadsTheValue();
double val2;
char* p1 = reinterpret_cast<char*>(&val1);
char* p2 = reinterpret_cast<char*>(&val2);
for(int i = 0; i < sizeof(uint64_t); i++)
    p2[i] = p1[i];

Droping this just as a fun fact, it's easier to just use memcpy as in @chqrlie's answer. Unless you can't use the C standard library.

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