Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 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 Reply

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...