how can I extract the mantissa of a double

心已入冬 提交于 2019-12-17 09:48:07

问题


I would like to store in a variable the mantisssa of a double

I have post a code to get the binary representation of a double : click here

What should I change to isolate the mantissa


回答1:


In <math.h>

double frexp (double value, int *exp)

decompose VALUE in exponent and mantissa.

double ldexp (double value, int exp)

does the reverse.

To get an integer value, you have to multiply the result of frexp by FLT_RADIX exponent DBL_MANT_DIG (those are availble in <float.h>. To store that in an integer variable, you also need to find an adequate type (often a 64 bits type)

If you want to handle the 128 bits long double some implementations provide, you need C99 frexpl to do the splitting and then you probably don't have an adequate integer type to store the full result.




回答2:


Many Linux systems have /usr/include/ieee754.h which defines bitfields for IEEE-format float, double and long double: you could trivially "port" it if necessary.




回答3:


The code here is a bit dangerous in terms of portability, but here it is...

#include <cstdint>

float myFloat = 100;
int32_t mantissa1 =
    reinterpret_cast<int32_t&>(myFloat) & (((int32_t)1 << 24) - 1);

double myDouble = 100;
int64_t mantissa2 =
    reinterpret_cast<int64_t&>(myDouble) & (((int64_t)1 << 53) - 1);


来源:https://stackoverflow.com/questions/5672960/how-can-i-extract-the-mantissa-of-a-double

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!