Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Float to Integer Equivalent

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?

like image 419
Dan Snyder Avatar asked May 05 '26 09:05

Dan Snyder


2 Answers

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.

like image 157
miked Avatar answered May 06 '26 21:05

miked


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);
like image 45
Oleh Prypin Avatar answered May 06 '26 21:05

Oleh Prypin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!