Note that there are some explanatory texts on larger screens.

plurals
  1. POConvert float to bigint (aka portable way to get binary exponent & mantissa)
    text
    copied!<p>In C++, I have a bigint class that can hold an integer of arbitrary size. </p> <p>I'd like to convert large float or double numbers to bigint. I have a working method, but it's a bit of a hack. I used IEEE 754 number specification to get the binary sign, mantissa and exponent of the input number.</p> <p>Here is the code (Sign is ignored here, that's not important):</p> <pre><code> float input = 77e12; bigint result; // extract sign, exponent and mantissa, // according to IEEE 754 single precision number format unsigned int *raw = reinterpret_cast&lt;unsigned int *&gt;(&amp;input); unsigned int sign = *raw &gt;&gt; 31; unsigned int exponent = (*raw &gt;&gt; 23) &amp; 0xFF; unsigned int mantissa = *raw &amp; 0x7FFFFF; // the 24th bit is always 1. result = mantissa + 0x800000; // use the binary exponent to shift the result left or right int shift = (23 - exponent + 127); if (shift &gt; 0) result &gt;&gt;= shift; else result &lt;&lt;= -shift; cout &lt;&lt; input &lt;&lt; " " &lt;&lt; result &lt;&lt; endl; </code></pre> <p>It works, but it's rather ugly, and I don't know how portable it is. Is there a better way to do this? Is there a less ugly, portable way to extract the binary mantissa and exponent from a float or double?</p> <hr> <p>Thanks for the answers. For posterity, here is a solution using frexp. It's less efficient because of the loop, but it works for float and double alike, doesn't use reinterpret_cast or depend on any knowledge of floating point number representations.</p> <pre><code>float input = 77e12; bigint result; int exponent; double fraction = frexp (input, &amp;exponent); result = 0; exponent--; for (; exponent &gt; 0; --exponent) { fraction *= 2; if (fraction &gt;= 1) { result += 1; fraction -= 1; } result &lt;&lt;= 1; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload