So i am about to read a 8bit pixel and want to convert the value to float (0..1) range
Like this
unsigned char r = get_pixel_from_img(x, y);
Now do i divide it by 255 or 256?
float fval = float ( r ) / x;
Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!
So i am about to read a 8bit pixel and want to convert the value to float (0..1) range
Like this
unsigned char r = get_pixel_from_img(x, y);
Now do i divide it by 255 or 256?
float fval = float ( r ) / x;
Hint:
The maximum value of an unsigned 8bit integer is 255. So which value do you get if you calculate 255/256? It is probably not 1 . More like 0.9xxxx So divide by 255.
Greetings
Normally for [0..1] you'd divide it by 255.
(0..1) ... you mean narrowing the integer range 0..255 down to the interval excluding 0.0 and 1.0 ?
Edit ninja'd ninja'd ...
If unsure, let the compiler figure it out for you ?. Here's two "generic" methods using limits.h:
constexpr auto ucharMax = std::numeric_limits<unsigned char>::max();
float value = pixel / float(ucharMax);
float value2 = pixel / float(UCHAR_MAX);
Or you could roll your own for any byte size (which in a general case is overwhelmingly likely but not actually guaranteed to be 8 bits)...
using byte_t = unsigned char;
const byte_t ucharMax = byte_t(0xffffffff); // support any size of uchar up to 64 bits
Or if you know the size of your byte... Use mad hax!