0

I'm trying to create a float by setting its bits. I read here that probably the best way is using memcpy. That's the code I'm using

#include <stdio.h>
#include <string.h>

float i2f(int i) {
  float result;

  memcpy(&result, &i, sizeof(int));

  return result;
}

int main() {
  printf("Size of int is %d.\n", sizeof(int));
  printf("Size of float is %d.\n", sizeof(float));

  int i = 0x7fffff;
  float f = i2f(i);

  printf("int value is %d.\n", i);
  printf("float value is %f.\n", f);

  return 0;  
}

The output I get is

Size of int is 4.
Size of float is 4.
int value is 8388607.
float value is 0.000000.

Can someone explain why float value is zero ?

zzz_zzz
  • 73
  • 4

1 Answers1

3

The bits of integer 0x7fffff encode a float value that is very small, less than 2−126. The %f conversion specifier does not produce enough digits to show the value. Use %g or %e or specify many more digits, such as %.99f.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312