public BitLattice Encode() { // --- Sign --- BitLattice b = new BitLattice(size); b.AddField(SignField, size - 1, 1); b.SetBool(SignField, sign); // writing sign // --- Regime --- int regimeSize; if (regime >= 0) { regimeSize = regime + 1; } else { regimeSize = -regime; } int regimePosition = size - 1 - regimeSize; int regimeTerminatorPosition = regimePosition - 1; b.AddField(RegimeField, regimePosition, regimeSize); for (int i = 0; i < regimeSize; ++i) { b[regimePosition + i] = regime >= 0; // writing regime } b.AddField(TerminatorField, regimeTerminatorPosition, 1); b[regimeTerminatorPosition] = regime < 0; // writing regime terminator // --- Exponent --- int exponentSize = Math.Min(es, size - 2 - regimeSize); if (exponentSize > 0) { int exponentPosition = regimeTerminatorPosition - exponentSize; b.AddField(ExponentField, exponentPosition, exponentSize); b.SetUint(ExponentField, (uint)exponent); } // --- Fraction --- int fractionSize = Math.Max(0, size - 2 - regimeSize - exponentSize); if (fractionSize > 0) { b.AddField(FractionField, 0, fractionSize); b.SetUint(FractionField, (uint)fraction); } return(b); }
public float ToFloat(out BitLattice fbits) { inexact = false; fbits = new BitLattice(32); // IEEE 754 int floatExpSize = 8; int floatFracSize = 23; fbits.AddField(SignField, fbits.Size - 1, 1); fbits.AddField(ExponentField, fbits.Size - floatExpSize - 1, floatExpSize); fbits.AddField(FractionField, 0, floatFracSize); int floatExpBias = 1 - (2 << (fbits.GetFieldLength(ExponentField) - 2)); // -127 int floatExp = FullExponent - floatExpBias; if (floatExp > (1 << floatExpSize) - 1) { floatExp = (1 << floatExpSize) - 1; inexact = true; } fbits.SetBool(SignField, sign); fbits.SetUint(ExponentField, (uint)floatExp); int fracResize = floatFracSize - FractionSize; uint floatFrac = fraction; if (fracResize < 0) { inexact = true; floatFrac >>= (-fracResize); } else if (fracResize > 0) { floatFrac <<= fracResize; } fbits.SetUint(FractionField, (uint)floatFrac); return(BitConverter.ToSingle(fbits.ToBytes())); }