Casting two pointers (float * to int *)

I am an IT student and I had a C Programming Exam today. One of the questions is a bit confusing: is it possible to convert float * to int *? I didn't say what you think?

+3


source to share


2 answers


You can create, but you can't magically get the integer version of the float.

What happens is that you have a float somewhere in memory and then there is a whole point at the same place. But they are presented differently (like two's complement vs IEEE 754 ) and you end up with a completely different integer as a result.

For example:

#include <stdio.h>

int main() {
  printf("sizeof(int) = %zu\n", sizeof(int));
  printf("sizeof(float) = %zu\n", sizeof(float));

  float m = 456.78f;
  int *p = (int*)&m;

  printf("Float:   %f\n", m);
  printf("Integer: %d\n", *p);

  return 0;
}

      



On my system, this gives:

sizeof(int) = 4
sizeof(float) = 4
Float:   456.779999
Integer: 1139041239

      

I also print their sizes to emphasize that they may vary. For example, if the integer turned out to be large, you then touched memory outside the float.

While this is probably not what you want, there is a use for it. For example, if you want to see a bit representation for a specific float, you can overlay it on something like uint8_t

and check it before sizeof(float)

.

+4


source


Why not just give it a try?

$ cat foo.c
#include <stdio.h>
int main(){
  float f = 0.15625;
  float *p = &f;
  printf("%f\n", *p);
  printf("%i\n", *((int *)p));
}
$ gcc foo.c
$ ./a.out
0.156250
1042284544

      

float

- 32 bits and you can read about how it was represented: http://en.wikipedia.org/wiki/Single-precision_floating-point_format



Casting a pointer float

to a pointer int

simply means telling C that "the data I'm pointing to is int

".

float

0.156250 is represented in binary 0111110001000000000000000000000

, which is an integer 1042284544

.

EDIT : @csl beat me to answer :)

+2


source







All Articles