Skip to main content
GameDev.net gamedev.net
🔒 Locked

Fast way to cast int to float!

Started by DedicatedGamer Mar 28, 2016 at 5:17 AM 14 replies 10.5k views
Original Post
DedicatedGamer
DedicatedGamer

This is a very fast way to cast an integer to a float. I use it extensively in my projects.

int ix = 58;

float fx = ix + 0.0;

SIMCUBE™ A video game I am making for no particular reason except that it is awesome!
Hodgman
Hodgman

Ironically that's almost a sane thing to do in Javascript to perform type coercion :lol:

TRWTF is that this is actually casting the into to double and then implicitly casting the double to float, which should produce a nasty compiler warning/error.

Ravyne
Ravyne

I would expect the fastest way is the most direct -- C or C++ style casts, assuming C++ as your language.

Its always hard to tell in Coding Horrors whether people are serious or trying to be funny -- if serious, what kind of profiling leads you to believe this is faster and what other methods are you testing against?

throw table_exception("(? ???)? ? ???");
Alberth
Alberth

Faster, as in less typing required :D

Sik_the_hedgehog
Sik_the_hedgehog

The sad thing is that fx = ix + 0.0f is actually different from fx = ix unless you're using something like -ffast-math (compilers can't optimize floating point operations because that can introduce different rounding errors and hence technically cause the result to be different, which is not allowed by the standard).

Don't pay much attention to "the hedgehog" in my nick, it's just because "Sik" was already taken =/ By the way, Sik is pronounced like seek, not like sick.
DedicatedGamer
DedicatedGamer

I actually do not know if this is actually faster, it just seems like it would be, because it is a single call as opposed to passing a variable to a function (proper typcasting).

int ix = 58;

float = (int) ix;

Also, I don't think it gives a compiler warning. I also do this a lot in my projects:

float fx = 1.983;

int ix = fx;

Which DOES produce a very nasty warning, so I disabled the warning for that specifically. :)

SIMCUBE™ A video game I am making for no particular reason except that it is awesome!
Ravyne
Ravyne

No, casting between primitive types shouldn't incur function-call overhead no matter how its spelled -- remember, compilers are amazing and just because something looks like a function call doesn't mean it is.

Both of those are bad, two strikes, and disabling the warning makes three.

If you mean to cast, use the language of a cast -- otherwise it obscures your intent and makes the job of understanding what you mean to happen harder for both humans and the compiler.

Case in point -- had you used a proper cast, explicitly, I think you'd not have gotten that warning in the first place -- or at least you could look at it trivially and know it was intentional rather than working out every time whether it was an unintentional bug or not.

Always be wary of ignoring warnings whether you disable them or you just glaze your eyes over -- Its impossible not to miss real bugs when you routinely flood yourself with warnings you'll simply ignore. When you really do need to disable a warning, you should do it as tightly as is practical. Using #pragmas you can disable a warning for a single-line of code, a few lines, one function, one source file, whatever -- tighter is better.

And don't complain that's a pain in the ass -- it is and it ought to be, because there's no reason you should be doing it so often that its a burden. If you reach for it enough to be a burden, its a good sign you're doing something horribly wrong.

Just stahp.

throw table_exception("(? ???)? ? ???");
Brain
Brain
Typecasting isn't always a function.

For static casts and C style casts it's done purely as a compile time operation or turned into a copy operation, you're telling the compiler "these four bytes that I said were an int? I was lying. They're actually a float, treat them as such and don't question me".

Of course for dynamic casts and certain types of conversion the runtime does checks and balances but these are both internal and inline as far as you're concerned.

The best thing to do is avoid static casts where you can, not because of speed but because you're essentially saying "hi compiler, please discard data". In the end if you want to fit your square peg in a round hole you're going to have to trim it to fit...
frob
frob




If you mean to cast, use the language of a cast -- otherwise it obscures your intent and makes the job of understanding what you mean to happen harder for both humans and the compiler.
Ah, you must be using one of those strongly typed languages, or a language where type rules are evaluated at compile time.

Javascript is the current darling at many companies, where HTML5 is everywhere. Weakly typed with dynamic type evaluation means evil things. Casting is automatic and is done behind your back. Dynamic casting (also called 'duck typing') coupled with automatic casting rules mean that whatever your data actually holds, either the system will find some terrible alternate type conversion that makes no sense to the programmer but is valid for the browser, or it will fail silently. Why is the page blank on this browser but works perfectly on three others? Nobody knows, and good luck getting the browser to tell you!

Python is also a mainstay of tools developers. Some systems work with it, but for most, compile-time evaluation is a dream. It is only at runtime you are allowed to discover if you provided all the functionality for duck typing. Any changes to any upstream library and suddenly you discover you need to add many new functions. But you cannot be told at compile time, only after it crashes when QA is abusing it. And heaven help you if your logging system doesn't immediately reveal what functions were expected but missing.

In somewhat related news, today a coworker said two words that were never meant to go together: "Enterprise JavaScript". With systems like node.js being more popular we are seeing the rise of abominations that should have been killed on sight, without mercy.

I told him I did not accept "Enterprise JavaScript" could possibly be a thing in a reality I participate in.

Hodgman
Hodgman




Also, I don't think it gives a compiler warning
If it doesn't, your compiler is configured wrong :wink:

Seriously though, in your project properties / compiler config, enable "warning level 3" and "treat warnings as errors" (on MSVC that's /W3 /WX).

Your future code will thank me.

FRex
FRex

Ironically that's almost a sane thing to do in Javascript to perform type coercion :lol:

Same for Lua 5.3 (the Lua version that sadly added ints to the language), it's discouraged and they say to use int or float depending on which you actually need but still mention that way to convert an int to float.

DedicatedGamer
DedicatedGamer

Calm down everyone, I was just kidding. :P

SIMCUBE™ A video game I am making for no particular reason except that it is awesome!
MikeWillHugYou
MikeWillHugYou

This is a very fast way to cast an integer to a float. I use it extensively in my projects.

int ix = 58;

float fx = ix + 0.0;

You can actually save a whole line:

int ix = 58;

float fx = ix - 0.0;

Geri
Geri

also, another interesting thing from most x86 cpu-s: multipling a float number with integer is faster than multipling two floats.

Sik_the_hedgehog
Sik_the_hedgehog



In somewhat related news, today a coworker said two words that were never meant to go together: "Enterprise JavaScript". With systems like node.js being more popular we are seeing the rise of abominations that should have been killed on sight, without mercy. I told him I did not accept "Enterprise JavaScript" could possibly be a thing in a reality I participate in.

https://twitter.com/0x0961h/status/767109252196491264

"Enterprise HTML5" has also been mentioned in that thread.

Don't pay much attention to "the hedgehog" in my nick, it's just because "Sik" was already taken =/ By the way, Sik is pronounced like seek, not like sick.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.