Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to convert float to int on x86

Tags:

What is the fastest way you know to convert a floating-point number to an int on an x86 CPU. Preferrably in C or assembly (that can be in-lined in C) for any combination of the following:

  • 32/64/80-bit float -> 32/64-bit integer

I'm looking for some technique that is faster than to just let the compiler do it.

like image 742
robottobor Avatar asked Sep 17 '08 00:09

robottobor


People also ask

How do you convert a float to an integer?

A float value can be converted to an int value no larger than the input by using the math. floor() function, whereas it can also be converted to an int value which is the smallest integer greater than the input using math. ceil() function.

Which method is used to convert integer data type to float?

Integer and Float Conversions Integers and floats are data types that deal with numbers. To convert the integer to float, use the float() function in Python.

Can float be implicitly converted to int?

Real floating-integer conversionsA finite value of any real floating type can be implicitly converted to any integer type.

Can float be converted to int in C?

The way to get the value is either the lib function int floor(float) or (for roundingup) int ceil(float).


1 Answers

It depends on if you want a truncating conversion or a rounding one and at what precision. By default, C will perform a truncating conversion when you go from float to int. There are FPU instructions that do it but it's not an ANSI C conversion and there are significant caveats to using it (such as knowing the FPU rounding state). Since the answer to your problem is quite complex and depends on some variables you haven't expressed, I recommend this article on the issue:

http://www.stereopsis.com/FPU.html

like image 78
Zach Burlingame Avatar answered Oct 19 '22 19:10

Zach Burlingame