![](/img/trans.png)
[英]If std::numeric_limits<float>::is_iec559 is true, does that mean that I can extract exponent and mantissa in a well defined way?
[英]how can I extract the mantissa of a double
在<math.h>
double frexp (double value, int *exp)
在指数和尾数中分解 VALUE。
double ldexp (double value, int exp)
反之。
要获得整数值,您必须将 frexp 的结果乘以 FLT_RADIX 指数 DBL_MANT_DIG(那些在<float.h>
可用。要将其存储在整数变量中,您还需要找到合适的类型(通常为 64 位)类型)
如果要处理某些实现提供的 128 位长 double,则需要 C99 frexpl 进行拆分,然后您可能没有足够的整数类型来存储完整结果。
许多 Linux 系统都有/usr/include/ieee754.h ,它定义了 IEEE 格式浮点、双精度和长双精度的位域:如果需要,您可以轻松地“移植”它。
这里的代码在可移植性方面有点危险,但这里是......
#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);
字符串化标记化方法:
#include <string.h>
#include <stdio.h>
long double example=(-10000.0/7.0);
long long ldoubtollmant(long double num)
{ char stackdump1[101]={'\0'};
char *dump1=&stackdump1[0];
char stackdump2[101]={'\0'};
char *dump2=&stackdump2[0];
snprintf(dump1,100,"%.15Le",num);
char *next1=dump1;
next1=strtok(dump1,"e");
char *next2=NULL;
strtok_r(next1,".",&next2);
snprintf(dump2,100,"%s%s",dump1,next2);
return atoll(dump2);}
short int ldoubtoshexp(long double num)
{ char stackdump1[101]={'\0'};
char *dump1=&stackdump1[0];
snprintf(dump1,100,"%.15Le",num);
char *next1=NULL;
strtok_r(dump1,"e",&next1);
return (short int)atoi(next1);}
int main(int argc,char *argv[])
{ printf("\n%lld",ldoubtollmant(example));
printf("\n%hd",ldoubtoshexp(example));}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.