简体   繁体   中英

Cast double to int64_t and back without info lost

This question has probably being asked, but I searched and could not find the answer.

I'm implementing a toy virtual machine, where the OpCodes take the form:

std::tuple<int8_t, int64_t, int64_t> // instruction op1, op2

I'm trying to pack a double into one of the operands and read it back again when processing it. This doesn't work reliably.

double d = ...
auto a = static_cast<int64_t>(d);
auto b = static_cast<double>(a)
// sometimes, b != d

Is there a way to pack the bit representation of the double into an int64_t, and then read that bit pattern back get the same exact double as before?

static_cast performs a value conversion - the fractionary part is always lost. memcpy is what you are after.

double d = ... 
int64_t a;
memcpy(&a, &d, sizeof(a));
double d2;
memcpy(&d2, &a, sizeof(d2));

Still, I would probably instead make the operands a union with a double and an int64_t (plus possibly other types that are interesting for your VM).

One way to make it work is to reinterpret the block of memory as int64_t/double, ie to do pointer casts:

double d = ...
auto *a = (int64_t*)&d;
auto *d2 = (double*)a;
auto b = *d2;
assert(d == b);

Note that we both assume here that double and int64_t are of the same size (64 bit). I don't remember now if it is a part of the standard.

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