Created
October 5, 2022 20:09
-
-
Save controlflow/8183b43cdc6473cc9a1841269d147c4b to your computer and use it in GitHub Desktop.
Denormal floating numbers playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Text; | |
PrintNumber(0f); | |
PrintNumber(-0f); | |
PrintNumber(1f); | |
PrintNumber(-1f); | |
PrintNumber(float.PositiveInfinity); | |
PrintNumber(float.NegativeInfinity); | |
PrintNumber(float.NaN); | |
PrintNumber(float.Epsilon); | |
PrintNumber(float.Epsilon * 2); | |
void PrintNumber(float value) | |
{ | |
var sb = new StringBuilder(); | |
sb.Append($"value={value,-20:R}"); | |
var bits = BitConverter.SingleToUInt32Bits(value); | |
sb.Append($" sign={bits >> 31}"); | |
var exponent = (byte) (bits >> 23); | |
var mantissa = (int) (bits & 0x7FFFFF); | |
if (exponent > 1 && exponent <= 254) | |
sb.Append($" exp={(sbyte)(exponent + 126),-6}"); | |
else if (exponent == 0) | |
sb.Append(mantissa == 0 ? " exp=zero " : " exp=denorm"); | |
else | |
sb.Append(" exp=notfin"); | |
sb.Append($" exp_biased={exponent,-3}"); | |
sb.Append($" exp_field={Convert.ToString(exponent, 2).PadLeft(8, '0')}"); | |
sb.Append($" frac_field={Convert.ToString(mantissa, 2).PadLeft(23, '0')}"); | |
Console.WriteLine(sb); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment