Reputation: 95
I have implement a function that converts a float color channel (R, G, B) to a byte value.
E.g.: 0.0f -> 0 1.0f -> 255
unsigned char RGBImage::convertColorChannel(float f) {
}
How can I get this results in C++?
Upvotes: 0
Views: 2270
Reputation: 2694
return f * 255;
, the cast from float
to unsigned char
is implicit because of the return-type.
return (f * 255) + 0.5;
to round the value correctly (since you are losing precision), but keep in mind that this is an extra calculation that will bring a performance hit. So if you are converting an entire high-resolution image, as the class name implies, then the additional calculation time may add up.
Upvotes: 3
Reputation: 340055
Trivially (if you'll excuse the C-style cast):
return (unsigned char)(f * 255);
Note that this does not check whether f
is correctly in the range [0.0 - 1.0]
Upvotes: 3