#### Archived

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.

## 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 on other sites
look up fixed point variables

##### 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

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

##### 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;
target1=temp;
float temp2 = source - (float) temp;
target2 = (int)( temp2 * PREC );
}

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

1. 1
2. 2
Rutin
20
3. 3
khawk
16
4. 4
A4L
14
5. 5

• 12
• 16
• 26
• 10
• 11
• ### Forum Statistics

• Total Topics
633756
• Total Posts
3013709
×