0
votes

I want to print the hexadecimal value of two floating point numbers in the IEEE standard representation (sign, 8 bit exponent, 23 bit mantissa). My problem is that the numbers that I random generate are super big (for example: -26815622280406798000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000) without any numbers after the point (only 0) and with sign.

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

float RandVectorGen(void);

int main () {

    srand(time(NULL));

    float Vectors_A = 0, Vectors_B = 0, Vectors_SUM = 0; 

            for(int i = 0; i <= 20; ++i) {
                
                Vectors_A = RandVectorGen();      //Genera 20 vettori tra 100 e 0
                Vectors_B = RandVectorGen();

                printf("Vettore %d_A: %x  =>  %.6f\n", i, Vectors_A, Vectors_A);
                printf("Vettore %d_B: %x  =>  %.6f\n", i, Vectors_B, Vectors_B);

                Vectors_SUM = Vectors_A + Vectors_B;            

                printf("Somma tra i due vettori: %x  =>  %.6f\n", Vectors_SUM, Vectors_SUM);

                puts(" ");

                }

    return 0;

}

float RandVectorGen (void) {

    
    unsigned int Vector1, Vector2;
    float RandomVector = ((float)Vector1 / (float)Vector2) * fabs(sin(rand() % 10));

        Vector1 = (rand() % 30);
        Vector2 = (rand() % 30);

    return RandomVector;
}

2
Do you mean "dump the raw form of the floating-point value as hexadecimal" or do you mean "dump the hexadecimal equivalent value"?tadman
Note, the indentation style used here is really chaotic and hard to follow.tadman
Yes i would like to print the raw form of floating-point like this: upload.wikimedia.org/wikipedia/commons/thumb/e/e8/…Gabbed
You can use the %a or %A printf format specifier to print a floating point value in hexadecimal.Ian Abbott
A common trick used to reinterpret the binary representation of a type as a different type (known as "type punning") is to use a union. For example union foo { float f; unsigned int ui; }; union foo x; x.f = Vectors_A;` printf("%x", x.ui);.Ian Abbott

2 Answers

2
votes

In the absence of flow control, C runs from top to bottom. So when you initialize RandomVector using two uninitialized variables, you get Undefined Behavior. It does not matter that you later assign two values to Vector1 and Vector2.

0
votes

Your RandomVector is random in the sense that it is based on uninitialized values, which is undefined behavior. You only assign values to Vector1 and Vector2 after that, but you never use those. You should try it like this:

float RandVectorGen (void)
{
    unsigned int Vector1, Vector2;
    float RandomVector;

    Vector1 = (rand() % 30);
    Vector2 = (rand() % 30);
    
    RandomVector = ((float)Vector1 / (float)Vector2) * fabs(sin(rand() % 10));

    return RandomVector;
}