how can I extract the mantissa of a double

前端 未结 4 1126
执笔经年
执笔经年 2020-12-01 16:37

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 chan

相关标签:
4条回答
  • 2020-12-01 17:13

    A stringify tokenizing approach:

    
    
        #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));}
    
    0 讨论(0)
  • 2020-12-01 17:25

    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.

    0 讨论(0)
  • 2020-12-01 17:30

    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.

    0 讨论(0)
  • 2020-12-01 17:37

    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);
    
    0 讨论(0)
提交回复
热议问题