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 re
you can use type casting ..
float x =3.4;
int y = (int)x;
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++.
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
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 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:
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?