Search code examples
c#floating-pointiterationsingle-precision

Iterate through single precision floating point numbers between [1,2)


I am working on program that requires me to iterate through all single precision floating point (23 fractions bits) numbers in the range of [1,2). I am not quite sure how to go about this. I am writing this program in C#.

If someone could give me some help with this, that would be awesome. Thank you!


Solution

  • You could use the BitConverter static class to convert float value to int and back. Thus you can access its bits.

    int one = BitConverter.ToInt32(BitConverter.GetBytes(1f), 0);
    int two = BitConverter.ToInt32(BitConverter.GetBytes(2f), 0);
    
    for (int i = one; i < two; i++)
    {
        float f = BitConverter.ToSingle(BitConverter.GetBytes(i), 0);
        // Your stuff
    }