Need Help with my code

0 comments

My code is currently not working out like I want it to , it is supposed to split up the three components of a floating point number into the sign, exponent and fraciton part of a 32 bit int. Here is the code:

#include <stdio.h>

#include <stdint.h>

#include <stdlib.h>

#include <assert.h>

#include “floats.h”

uint32_t u;

uint32_t sign;

uint32_t exponent;

uint32_t fraction;

// separate out the 3 components of a float

float_components_t float_bits(uint32_t f) {

sign = ((f>> 31) & 0x1);

exponent = ((f >> 30) & 0x7F);

fraction = ((f >> 23) & 0xFFFFFF);

}

Floats.h

#include <stdio.h>

#include <stdint.h>

#include <stdlib.h>

#include <assert.h>

/// We use `union overlay’ to obtain the raw bits of a `float’-type

/// value, by storing the `float’ in the `f’ field and then using the

/// `u’ field to obtain the bits.

union overlay {

float f;

uint32_t u;

};

/// A struct suitable for storing the three components of a `float’.

typedef struct float_components {

uint32_t sign;

uint32_t exponent;

uint32_t fraction;

} float_components_t;

/// For the `float_bits’ exercise:

float_components_t float_bits(uint32_t bits);

int is_nan(float_components_t f);

int is_positive_infinity(float_components_t f);

int is_negative_infinity(float_components_t f);

int is_zero(float_components_t f);

/// For the `float_2048′ exercise:

uint32_t float_2048(uint32_t f);

/// For the `float_less’ exercise:

uint32_t float_less(uint32_t bits1, uint32_t bits2);

/// For the `float_print’ exercise:

void float_print(uint32_t f);

Test Float_bits

#include <stdio.h>

#include <stdint.h>

#include <stdlib.h>

#include <assert.h>

#include “floats.h”

int main(int argc, char *argv[]) {

for (int arg = 1; arg < argc; arg++) {

union overlay input;

input.f = atof(argv[arg]);

float_components_t c = float_bits(input.u);

printf(“float_bits(%.9g) returnedn”, input.f);

printf(“sign=0x%xn“, c.sign);

printf(“exponent=0x%02xn”, c.exponent);

printf(“fraction=0x%06xn”, c.fraction);

printf(“is_nan returned %dn”, is_nan(c));

printf(“is_positive_infinity returned %dn”, is_positive_infinity(c));

printf(“is_negative_infinity returned %dn”, is_negative_infinity(c));

printf(“is_zero returned %dn”, is_zero(c));

}

return 0;

}

I am really stuck and not sure what to do please any help would be much appreciated

About the Author

Follow me


{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}