public IEnumerable<float> Enumerate(FloatDescription desc) { var max = Math.Pow(2, desc.BitCount); for (var i = 0; i < max; i++) { var bcount = desc.BitCount / 8; if (desc.BitCount % 8 != 0) { bcount += 1; } var bytes = BitConverter.GetBytes(i).Take(bcount).Reverse().ToArray(); var value = FromBytes(desc, bytes); yield return value; } }
public float FromBytes(FloatDescription desc, params byte[] bytes) { var remainder = desc.BitCount % 8; var byteCount = desc.BitCount / 8; if (remainder > 0) { byteCount += 1; } if (bytes.Length > byteCount) throw new Exception("too many bytes"); var newBytes = bytes.Take(byteCount).ToArray(); var bits = newBytes.SelectMany(ByteToBits).Take(desc.BitCount).ToArray(); var floatParts = ToFloatParts(desc, bits); var value = FromFloatParts(desc, floatParts); return value; }
public float FromFloatParts(FloatDescription desc, FloatParts parts) { var isZero = true; var sign = parts.Sign > 0 ? -1 : 1; var e = BitsToInt(parts.Exponent) - desc.ExponentBias; if (e != 0) { isZero = false; } var exp = Math.Pow(2.0, e); double frac = 0; frac += 1; for (var i = 0; i < desc.SignificandBits; i++) { if (parts.Fraction[i] == Bit.One) { frac += Math.Pow(2.0, -(i + 1)); isZero = false; } } if (isZero) { return 0; } return (float)(sign * frac * exp); }
public FloatParts ToFloatParts(FloatDescription desc, Bit[] bits) { if (bits.Length != desc.BitCount) { throw new Exception("not enough bits"); } var e = new List<Bit>(); var f = new List<Bit>(); if (desc.ExponentBits > 0) { e = bits.Skip(1).Take(desc.ExponentBits).ToList(); } if (desc.SignificandBits > 0) { f = bits.Skip(1 + desc.ExponentBits).ToList(); } var parts = new FloatParts { Sign = bits[0], Exponent = e.ToArray(), Fraction = f.ToArray() }; return parts; }