graphicsencodingfloating-pointcgrgba

Encoding data in an 8-bit float (cg)


The language is cg.

I have an 8-bit float that must be between 0 and 1 (it's the 'a' component of a float4 rgba color value). I want to store a 6-bit unsigned integer and a 2-bit unsigned integer in that. How can I safely store these two values in those 8 bits?

I couldn't find any documentation on the format of an 8-bit float, especially one limited between 0 and 1. I'm assuming it's more complicated than just data / 255 ?


Solution

  • The OpenGL standard guarantees that at least 256 distinct values are preserved when writing to an 8-bit framebuffer. I’m pretty sure Cg does the same.

    So you should be able to write your two values in this way:

    output.a = (4.0 * clamp(val1, 0.0, 63.0)
                    + clamp(val2, 0.0, 3.0)) / 255.0;
    

    And retrieve them like this:

    float val1 = floor(input.a * 255.0 / 4.0);
    float val2 = fmod(input.a * 255.0, 4.0);
    

    This is equivalent to bitwise operations on integers.