Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double from long bits

I have an unsigned long long (or uint64_t) value and want to convert it to a double. The double shall have the same bit pattern as the long value. This way I can set the bits of the double "by hand".

unsigned long long bits = 1ULL;
double result = /* some magic here */ bits;

I am looking for a way to do this.

like image 684
pvorb Avatar asked Jul 01 '13 16:07

pvorb


People also ask

How many bits is a long double in C?

With the GNU C Compiler, long double is 80-bit extended precision on x86 processors regardless of the physical storage used for the type (which can be either 96 or 128 bits), On some other architectures, long double can be double-double (e.g. on PowerPC) or 128-bit quadruple precision (e.g. on SPARC).

What is longbitstodouble() method of Java double class?

The longBitsToDouble () method of Java Double class returns the double value equating to an acknowledged bit representation. Positive infinity, if the argument passed is 0x7ff0000000000000L. Negative infinity, if the argument passed is 0x7ff0000000000000L. bits - is the long integer passed.

What is the value of longbitstodouble?

bits - is the long integer passed. The longBitsToDouble () method returns a floating point value of type double with identical bit pattern. Float value after conversion = 3.7928E-316 Float value after conversion = 2.40447E-319 Float value after conversion = NaN

What is the use of doubletolongbits in Java?

The java.lang.Double.doubleToLongBits () method of Java Double class is a built-in function in java that returns a representation of the specified floating-point value according to the IEEE 754 floating-point “double format” bit layout.


2 Answers

The portable way to do this is with memcpy (you may also be able to conditionally do it with reinterpret_cast or a union, but those aren't certain to be portable because they violate the letter of the strict-alias rules):

// First, static assert that the sizes are the same
memcpy(&result, &bits, sizeof(bits));

But before you do make sure you know exactly what you're doing and what floating point representation is being used (although IEEE754 is a popular/common choice). You'll want to avoid all kinds of problem values like infinity, NaN, and denormal numbers.

like image 82
Mark B Avatar answered Sep 24 '22 07:09

Mark B


Beware of union and reinterpret_cast<double*>(&bits), for both of these methods are UB. Pretty much all you can do is memcpy.

like image 34
Puppy Avatar answered Sep 22 '22 07:09

Puppy