Jump to content
  • Advertisement


This topic is now archived and is closed to further replies.


float to two ints

This topic is 5645 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I want to convert a float to two ints, that is the first integer holds everything thats to the left of the decimal point and the second integer holds everything thats right of the decimal point. Any ideas?

Share this post

Link to post
Share on other sites
Depending on the precision you want if you use doubles(64bits) or floats (32 bits).

It's nearly the same thing as fixed point conversion. There is a C math function that does it (forgot the name but ez o find) exactly what you want.

If you want a really fast function seek info about the ieee floating point format that is the bitfield contained in a float (sign s, biased exponent e, mantissa m).
Which you can get by reading memory as an int, a C pointer cast :

int32 i = *((int32*)&f)

I think for a float the formula is something like : (-1)^s*(2^(e-128))*(1+m/2^23)

There's the big (or magic) number addition trick for quick conversion that lets you shift the bits the right way so that you can access the result in memory with a cast to convert directly to integers, get the first 32 bits to get the fractionnal part (fp) and get the next 32 bits and clear the exponent with a and to get the integer part (ip). Beware that's on a little endian processor. With big endian the memory mapping is in opposite order (ip, fp). If you want all the decimal bits from a float you can use this trick with a double. This is the fastest way I know. Would be tedious to explain here.

Try the C function if you understood nothing

Google search ...

[edited by - Charles B on July 4, 2003 7:25:51 PM]

Share this post

Link to post
Share on other sites
A dirty way to do it

#define PREC 100000.0f // numbers of digits behind the ''.''

void FloatToTwoInts(float source, int &target1, int& target2)
int temp;
temp = (int) source;
float temp2 = source - (float) temp;
target2 = (int)( temp2 * PREC );

Share this post

Link to post
Share on other sites
Or you can simply use integer division and modulus. Not the quickest way probably, but it''ll work.

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!