Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You want to convert 32 bit floats to 16 bit integers with scaling. However, the example you give uses a decimal scaling and not a binary. I'm unsure if you want to keep working in the binary domain on a system without a floating point unit or if you actually want to convert to decimal representation of the number.</p> <p>Here I assume that your challenge is that you don't have access to floating point instructions. You haven't specified a programming language so I decided to code some stuff in C#. The language is easy to use but perhaps not the most suited for bit fiddling. You may find it easier and more efficient to implement this in say C or C++.</p> <p>As I'm going to keep using a binary representation the scale cannot be a number like 10 or 100 (an integral power of 10) but instead has to be an integral power of 2. Below is a class to take an IEEE 754 binary32 floating point number apart.</p> <pre><code>class Ieee754Binary32 { public Ieee754Binary32(Single value) { using (var memoryStream = new MemoryStream()) { var binaryWriter = new BinaryWriter(memoryStream); binaryWriter.Write(value); memoryStream.Seek(0, SeekOrigin.Begin); var binaryReader = new BinaryReader(memoryStream); var bits = binaryReader.ReadInt32(); Fraction = bits &amp; 0x7FFFFF; Exponent = ((bits &gt;&gt; 23) &amp; 0xFF) - 127; Sign = (bits &amp; 80000000) == 1 ? -1 : 1; } } public Int32 Fraction { get; private set; } public Int32 Exponent { get; private set; } public Int32 Sign { get; private set; } public Int16 ToScaledInt16(Int32 scaling) { if (Exponent == -127 &amp;&amp; Fraction == 0) return 0; var mantissa = 0x8000 | (Fraction &gt;&gt; 8); var unscaledInt32 = Exponent &gt;= 0 ? mantissa &lt;&lt; Exponent : mantissa &gt;&gt; -Exponent; var scaledInt16 = unscaledInt32 &gt;&gt; (15 - scaling); return (Int16) (Sign*scaledInt16); } } </code></pre> <p>The method <code>ToScaledInt16</code> is what you want to use. If you want to express numbers using fractions of 8 you should supply the value <code>3</code> for <code>scaling</code>. All number will be multiplied by <code>2^3 = 8</code>, e.g. 0.125 = 1/8 is converted to 1, 0.25 = 2/8 to 2 etc.</p> <p>The code does not handle more complex stuff like rounding, NaN or overflow but perhaps you can use it as a starting point?</p>
 

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