Basically I have a uint64_t
whose actual value I do not care about. I need to store it in a double
so that I can easily store the bits in an object in R (if you don't know what that is, that's fine, it doesn't matter for the question).
So what I would like is a means of storing the 64 bits of the uint64_t
inside of a double
and then also convert from the double
holding the bits back to the original uint64_t
.
I've been banging my head against the wall on this for a quite a bit (is that a pun?) so any and all help is greatly appreciated!!!
As stated in the comments, you can use memcpy to copy the bits from your uint64_t
to a double
.
This works because the size of a double
is the same as the one of an uint64_t
(8 bytes).
If you try to display the values, you won't get the same result, though. Indeed a double stores both positive and negative values, with a floating point, whereas an uint64_t
is... unsigned and whole.
The binary representation is the same, the interpreted value is different.
in C casting is your friend:
example:
#include <stdint.h>
#include <inttypes.h>
#include <stdio.h>
double dbl_1 = 42.42;
uint64_t ui64_1;
double dbl_2;
uint64_t ui64_2 = 0x404535C28F5C28F6;
void main(void)
{
ui64_1 = *(uint64_t*)(&dbl_1);
printf("%" PRIx64 "\n", ui64_1);
dbl_2 = *(double*)(&ui64_2);
printf("%f", dbl_2);
}
Great resource for conversions: IEEE-754 Floating-Point Conversion
Edit: This is undefined behavior per the C standards and although it may work, it is not best practice.
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.