احمد -4 years ago 134
C Question

# Converting float from 0 to 1 to RGB 16bit

I would like to convert a float to RGB 16bit. The float range is from 0 to 1. The RGB format is 5bits for Red, 6 bits for Green, 5 bits for Blue.
So to clarify more, 0 is fully black and 1 is fully bright.

`````` // 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;
// shade is unsigned short

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

}
} // end if use flat shading
``````

``````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, 6msb mask

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

live demo: http://ideone.com/npLpB7

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download