Linked to: GLSL pack floats into an RGBA texture

I found EncodeFloatRGBA/DecodeFloatRGBA shader functions in Unity https://gist.github.com/hecomi/9580605

Now I try to figure out how they work. So I try them on C++ http://coliru.stacked-crooked.com/a/345f8c403d4a78f9

But I got wrong results. Also I tried that with Mathematica, and got the same wrong results. http://www.sendspace.com/file/qmlu8b

I tried to encode {0.1, 0.2, 0.3, 0.4} - but after encode/decode got {0.0980392,0.698039,0.79649,0.93266}

  • 2
    \$\begingroup\$ What is your actual question? \$\endgroup\$
    – user1430
    Commented Apr 29, 2014 at 23:40
  • \$\begingroup\$ I want to pack two 4bit values into 8bit float. And search they way to do this. And that solution from Unity not work on C++, I wonder why. \$\endgroup\$
    – tower120
    Commented Apr 29, 2014 at 23:44

1 Answer 1


I got wrong results due to use of numbers which are not fraction of 255. In example used 255 (max int number of 8bit), so all numbers used in encoding/decoding should be a fraction of 255.

{0.1, 0.2, 0.3, 0.4} is not a fraction of 255, it is fraction of 10 or 100 or 1000...
With values like {1/255, 2/255, 3/255, 4/255} it works ok.

So when one use pack functions like that - pay attention to this. Actually you rather store integer values (which divided by number base) than float.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .