I am trying to convert a float directly into an unsigned integer WITHOUT ANY OF THE IMPLICIT CONVERSION MATH, (so not the C style or static casts) just copying the bytes directly to the other. In Windows Visual Studio 2015, the sizes for a float and a unsigned integer are the same, (4 Bytes) so I don't think there is any problem on that end . . . I came up with a solution but there has got to be a better way to do what I want.
unsigned int x = 3;
float y = 2.4565;
*reinterpret_cast<float*>(&x) = y;
This does what I want and sets X to 1075656524.
I would prefer a cross-platform solution, if there is one. I know the sizes of types can vary from platform to platform, so that might be impossible.
EDIT: To clarify, I want all of the bytes of the float copied into the unsigned int unchanged. Every single bit stored in the float should be stored in the unsigned integer. Also is there a solution that does not use memcpy? I want to avoid using deprecated functions.
I am trying to convert a float directly into an unsigned integer WITHOUT ANY OF THE IMPLICIT CONVERSION MATH, (so not the C style or static casts) just copying the bytes directly to the other
It seems like all you want to do is copy the bit pattern from one memory location to another. The standard library function memcpy
can be used for that. Just realize that if sizeof(int)
is different than sizeof(float)
, all of this is moot.
unsigned int x = 3;
float y = 2.4565;
static_assert(sizeof(int) == sizeof(float), "Can't memcpy a float to an int");
memcpy(&x, &y);
A more portable solution would be to use an array of uint8_t
or int8_t
.
uint8_t x[sizeof(float)];
float y = 2.4565;
memcpy(x, &y);
Now you can examine the bit pattern by examining the values of the elements of the array.