在C中获取浮点型变量的整型表示值 [英] get the integer representation value of a float type variable in C
本文介绍了在C中获取浮点型变量的整型表示值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include< stdio.h>
int main()
{
float f = 2.802597e-44;
int nv,* pnv;
printf(f =%f \ n,f);
printf(n =%d \\\
,f);
nv =(int)f;
printf(n =%d \\\
,nv);
pnv =(int *)& f;
printf(n =%d \\\
,(* pnv));
返回0;
$ b我得到了我想要的pnv整数指针。有没有更好的办法做到这一点避免指针和工作在C?
解决方案你可以实现你的需要与联合: / p>
#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);
返回0;
}
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\n",f);
printf("n=%d\n",f);
nv=(int)f;
printf("n=%d\n",nv);
pnv=(int*)&f;
printf("n=%d\n",(*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?
解决方案 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\n",fi.f);
printf("n=%d\n",fi.i);
return 0;
}
这篇关于在C中获取浮点型变量的整型表示值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文