C ++ portable long to double conversion

I need to accurately convert the long representing bits to double, and my soluton should be portable to different architectures (being able to be standard for compilers, since g ++ and clang ++ woulf will also be large). A.

I am writing a quick approximation to calculate the exp function, as suggested in this question answers .

double fast_exp(double val) { double result = 0; unsigned long temp = (unsigned long)(1512775 * val + 1072632447); /* to convert from long bits to double, but must check if they have the same size... */ temp = temp << 32; memcpy(&result, &temp, sizeof(temp)); return result; } 

and I use the suggested sentence here to convert long to double. The problem I am facing is that although I got the following results for int values ​​in [-5, 5] in OS X using clang ++ and libC ++:

 0.00675211846828461 0.0183005779981613 0.0504353642463684 0.132078289985657 0.37483024597168 0.971007823944092 2.7694206237793 7.30961990356445 20.3215942382812 54.8094177246094 147.902587890625 

I always get 0 under Ubuntu using clang ++ (3.4, same version) and libstd ++. The compiler even tells me there (with a warning) that the switch operation can be problematic, since the length is the size equal to or less than the shift parameter (indicating that long and double sizes do not have the same size)

Am I doing something wrong and / or is there a better way to solve the problem as compatible as possible?

+1
source share
1 answer

Firstly, using "long" is not portable. Use the fixed lengths of integer types found in stdint.h. This will make it easier to check for the same size, as you will know what size the whole will be.

The reason you get the warning is because a left shift of 32 bits in a 32-bit intger is undefined behavior. What's wrong with swapping a 32-bit 32-bit variable?

Also see this answer: Is it possible to consider sizeof (double)> = sizeof (void *)? . It is safe to assume that double is 64 bits, and then you can use uint64_t to store raw hexadecimal code. There is no need to check the sizes, and everything is portable.

+4
source

Source: https://habr.com/ru/post/1012015/


All Articles