R.Mckemey R.Mckemey - 3 months ago 10
C++ Question

Make a floating point number from a binary string in C++

I want to take a random string of 32 bits and declare this bit string to be a float in

C++
.

For example the string
0.0111 1111.1000 0000 0000 0000 0000 000
should give me the float corresponding to
1.5
as this is the F32 definition of 1.5 according to IEEE 754-2008. The first 0 mean +ve, the next 8 give you an exponent of 127-127 = 0, and the 23 bit mantissa gives you the
.5
.

If a string is not a good data format for this then I'd be happy to hear suggestions.

In fact I want to create a random floating point number in C++ but I don't know how. Where by random I mean each bit is independently 0 or 1. The solutions (for example here: C++ random float number generation) I've found suggest using a random integer generator then dividing by the
RAND_MAX
and then multiplying by
FLOAT_MAX
or in some other way creating a float according to some uniform distribution. This is no good to me as whilst the values will be evenly distributed, this will generate more floats with large exponents.

Basically this question but for C++: Convert Double to Binary representation?

Answer

If you just want a RNG that spits out a exponentially distributed floats, you don't have to worry about binary representation. Just use math.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <math.h>

int main (void) {
    int i;

    srand (time(NULL));

    // Make 10 'random' floats
    for (i = 0; i < 10; ++i)
    {
        // Float exponents go from -128 to 127
        float exponent = -128 + 256 * (float) rand() / RAND_MAX;

        float result = pow(2, exponent);

        printf ("%g\n", result);
    }

    return 0;
}

If you want to arbitrarily generate bytes interpreted as float, you can do this instead...

int i = rand();
float result = *((float *)&i);

printf ("%g\n", result);