4

I've created my own fixed-type integer types and the library works fine with many compilers and platforms, the only problem left to solve is to convert from built-in float-point types to my types.

The float-point types may have small mantissa but along with exponent it may have big value so if i choose to cast float, double, or long double say to long long or unsigned long long a truncation may occur.

If the compiler use IEEE-754 specification it'll be easy to extract mantissa and exponent, but what if the compiler use some other format.

So, my question: is there any generic algorithm that allows me to extract the full value from a float-point using only the language features?

thanks

Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
Muhammad
  • 1,598
  • 3
  • 19
  • 31
  • 2
    You could get a good insight about the characteristics of the FP types on the current platform by using the `std::numeric_limits` members; from that you can determine the radix and the size of the mantissa, thus determining by what you have to multiply the number to get the whole mantissa out when casting to an integer (also, you get to know if is there available any integer big enough for this to work). – Matteo Italia Feb 24 '13 at 23:08
  • 1
    CHeck out the [`frexp`](http://en.cppreference.com/w/cpp/numeric/math/frexp) family of functions. – Kerrek SB Feb 24 '13 at 23:32

1 Answers1

5

You may find useful my answer to a somewhat similar question here. The idea is that if the underlying format is binary, you are pretty much guaranteed to be able to extract the mantissa and exponent without loss if there are no more bits in the mantissa than there are in the biggest integer type. You can use double frexp(double value, int *exp); and double ldexp(double x, int exp); for the purpose.

Another option would be to sprintf() the number using %a to get all the digits and then manually convert the textual representation into what you need.

Community
  • 1
  • 1
Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180