احمد احمد - 25 days ago 7
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;
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

Answer
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