Float to Int

This felt like discovering penicillin!


If you have a float that you need to convert to an integer, and you know beforehand that the float is going to be in the range [0, 1), you can do the following in order to convert to a fixed point integer:

  • Add 1.0f
  • Keep the 23 least significant bits (n &= 0x7FFFFF)

There are certain machines where this is actually multiple times faster than a normal C cast.

It was a shock for me to find out that converting floats to/from integers can be expensive. There are a lot of techniques and optimizations but I kept this one in mind for future use, which is the simplest, and most of the times in graphics we deal with normalized quantities anyway.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s