将float从0转换为1到RGB 16bit

时间:2016-11-11 20:15:58

标签: c embedded

我想将浮点数转换为RGB 16位。浮点范围从0到1. RGB格式为红色5位,绿色6位,蓝色5位。 因此,为了澄清更多,0是完全黑色,1是完全明亮。

 // dot product 
    if (dp > 0)
                {
                    unsigned short color = color;
                    float intens ;
                    intensity = ambient_light + dp;

                    if (intensity > 1)
                        intensity = 1;
                    if (intensity < 0)
                        intensity = 0;

                    // intensity now varies from 0-1, 0 being black or grazing and 1 being
                    intens= color*intensity;
                    the_object->polys[curr_poly].shade = intens;
           // shade is unsigned short

                } // end if light is reflecting off surface
                else{
                    float color = the_object->polys[curr_poly].color*ambient_light;

                    the_object->polys[curr_poly].shade = color;
                }
            } // end if use flat shading

1 个答案:

答案 0 :(得分:1)

uint16_t floatToRGB565(float input)
{
    uint8_t x = input*255;
    uint8_t r = (x&248u);//0xff-0x07, 5msb mask
    uint8_t g = (x&252u);//0xff-0x03, 6msb mask
    uint8_t b = (x&248u);//0xff-0x07, 5msb mask

    return (r<<8)|(g<<3)|(b>>3);// assuming r is at msb
}

现场演示:http://ideone.com/npLpB7