Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
652 views
in Technique[技术] by (71.8m points)

floating point - get the integer representation value of a float type variable in C

I have the number 20 (0x14) stored in a 32-bit register. The register is allocated to a C float variable representing the value 2.8e-44. Now I want to get the hexadecimal representation of the float variable back and stored it into an integer variable in order to restore the original meaning of the information. Is there a better way to do that, apart from doing some pointer business? Here is the code:

#include <stdio.h>

int main()
{
    float f = 2.802597e-44;
    int nv,*pnv;
    printf("f=%f
",f);
    printf("n=%d
",f);
    nv=(int)f;
    printf("n=%d
",nv);
    pnv=(int*)&f;
    printf("n=%d
",(*pnv));
    return 0;
}

I get what I want using the pnv integer pointer. Is there a better way to do that avoiding pointers and working in C?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can achieve your need with a union:

#include <stdio.h>

int main()
{
  union { int i; float f; } fi;
  fi.f = 2.802597e-44;
  printf("f=%e
",fi.f);
  printf("n=%d
",fi.i);
  return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...