Monthly Archives: April 2014

Converting int to float while preserving it’s binary layout

So it happened today that I was forced to use a library in C++ which stores RGB8 colors in float. I personally think it is a really bad design decision but I had to deal with that.

Simple function like the following one doesn’t work:

The problem is that the uint32_t is implicitly converted to float and the binary layout is lost.

After a quick google search I had arrived at this:

It works correctly and maybe it is an idiomatic way to achieve this but to me it seems a bit hacky. After a while I had recalled unions and decided to use the following code:

It is a bit longer but to me it seems much more readable. Also my inner geek is satisfied that I’ve used union and it actually made sense (: