Reputation: 385
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?
Upvotes: 2
Views: 645
Reputation: 67929
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;
}
Upvotes: 5
Reputation: 234885
Note that the behaviour of (int*)&f
is undefined as the pointer types are unrelated. So don't approach the problem in that way.
Having checked that sizeof(float)
is the same as sizeof(int)
, you could do this in one of two ways:
1) Type pruning through a union
consisting of a float
, and an int
. Set the union
using one member, and read it back with the other.
2) memcpy
the contents of a variable of one type to the location of the variable of the other type.
Of these I prefer (2): (1) might be undefined with older C standards, and (2) also works well with C++.
Upvotes: 2
Reputation: 318
C is considered a weakley typed langauge, which may allow to assign values that belong to different types than the variable they are being assigned with, therefore you can simply do this:
int integer = 1;
float floater =1.1111;
floater = integer;
This is known as Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler. Some programming languages allow compilers to provide coercion; others require it.
but consider the following:
Upvotes: -2
Reputation: 73444
What are you doing there is Undefined Behavior, didn't you check the warning?
warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat=]
printf("n=%d\n",f);
^
Read this please: How do the digits 1101004800 correspond with the number 20?
Upvotes: 0
Reputation: 127
You can directly cast it to integer as;
float a = 7.4;
int b = a; // this will be rounded to 7 and you will lose information
Or you can use some built-int functions like round, ceil, floor etc.
For reference: http://www.cplusplus.com/reference/cmath/round/?kw=round
Upvotes: 1