Reputation: 1519
I want to convert a floating point user input into its integer equivalent. I could do this by accepting an input string, say "-1.234" and then I could just explicitly convert each character to it's decimal representation. (big endian by the way). So I would just say for the example I gave,
-1.234 = 1|01111111|00111011111001110110110
sign bit = 1 = 128<<31
exponent bits = 01111111 = 127<<23
mantissa bits = 00111011111001110110110 = 1962934
decimal equivalent = 1962934 + 127<<23 + 128<<31
This is easy enough but unwieldy. Is there a better way to do this? Maybe some sort of type casting I can do?
Upvotes: 2
Views: 4923
Reputation: 13187
In case you needed to convert a simple value, without an additional variable:
#define float_to_int(f) (*reinterpret_cast<const int*>(&static_cast<const float&>(f)))
Upvotes: 0
Reputation: 482
The standard way to re-interpret bit patterns is to use memcpy. If I recall correctly, gcc allows the pointer-type-casting *(int*)&a
as extension, but it is not guaranteed by the standard, and does not work with all compilers. Similarly, unions are not guaranteed to work.
#include <stdio.h>
#include <string.h>
float f = -1.234;
int i;
memcpy(&i, &f, sizeof i);
printf("bit pattern is: %d\n", i);
With optimization, the call to memcpy will be completely eliminated from the generated machine code.
Upvotes: 2
Reputation: 34116
float a = -1.234;
int b = *(int*)&a;
Also, in C++ there's this conversion operator that doesn't do any checks, reinterpret_cast
. It's probably better here.
int b = *reinterpret_cast<int*>(&a);
Upvotes: 3
Reputation: 3598
A union lets you access the same piece of memory as different types
union floatint
{
float f;
int i;
}
floatint fi;
fi.f=-1.234;
int i=fi.i;
warning: you can get into weird platform differences and things like that because of size and alighnment, but since you're already making some assumptions by trying to interpret the float as an int, you may be able to get away with it. Read more about unions, I think that's what you're going to want.
Upvotes: 7