R.Mckemey R.Mckemey - 11 months ago 43
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


For example the string
0.0111 1111.1000 0000 0000 0000 0000 000
should give me the float corresponding to
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

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
and then multiplying by
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 Source

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);