Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to turn a double to a 64-bit integer bit by bit using unions

I would like to store all bits of a double in a 64-bit integer in C.

I.e. the most significant bit should be the sign, after that the exponent, then the fraction.

I would like to use a union.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The safest way to do this is to use memcpy.

double x = 123.456;
uint64_t y;
memcpy(&y, &x, sizeof y);

If you don’t have memcpy at your disposal, you can use a union:

union {
    double d;
    uint64_t i;
} u;

double x = 123.456;
uint64_t y;

u.d = x;
y = u.i;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading