在C中获取float类型变量的整数表示值

我将数字20(0x14)存储在32位寄存器中。 寄存器分配给表示值2.8e-44的C float变量。 现在我想得到float变量的hex表示并将其存储到整数变量中,以恢复信息的原始含义。 除了做一些指针业务之外,还有更好的方法吗? 这是代码:

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

我使用pnv整数指针得到我想要的东西。 有没有更好的方法来避免指针和在C中工作?

您可以通过工会满足您的需求:

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

请注意, (int*)&f的行为未定义,因为指针类型不相关。 所以不要以这种方式解决问题。

检查sizeof(float)sizeof(int)相同后,您可以通过以下两种方式之一完成此操作:

1)通过由floatint组成的union类型修剪。 使用一个成员设置union ,并用另一个成员读回。

2)将一种类型的变量的内容memcpy到另一种类型的变量的位置。

其中我更喜欢(2):( 1)可能未使用较旧的C标准进行定义,(2)也适用于C ++。

您可以直接将其转换为整数;

 float a = 7.4; int b = a; // this will be rounded to 7 and you will lose information 

或者你可以使用一些内置的函数,如圆形,细胞,地板等。

供参考: http : //www.cplusplus.com/reference/cmath/round/?kw = around

你可以使用类型铸造..

 float x =3.4; int y = (int)x; 

你在做什么是未定义的行为 ,你没有检查警告?

 warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=] printf("n=%d\n",f); ^ 

请读一下: 数字1101004800如何与数字20对应?

C被认为是弱类型语言,它可以允许分配属于不同类型的值而不是它们被赋值的变量,因此您可以简单地执行此操作:

  int integer = 1; float floater =1.1111; floater = integer; 

这称为隐式类型转换,也称为强制转换,是编译器的自动类型转换。 一些编程语言允许编译器提供强制; 其他人需要它。

但请考虑以下事项:

  • 当浮点数小于零时会发生什么?