# C++ Silly question about reading pixels math

## Recommended Posts

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;

##### Share on other sites
Posted (edited)

Think about it: a byte goes from 0..255, so 0.0..1.0 = divide by 255.0

Edited by vinterberg
spelling

##### Share on other sites

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

##### Share on other sites
Posted (edited)

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 ...

Edited by Green_Baron

##### Share on other sites

Yeah, dont tell anyone i asked that...

##### Share on other sites

I won't

I made my last off by one error just yesterday ;-)

##### Share on other sites

Your secret is safe.

##### Share on other sites
Posted (edited)

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!

Edited by irreversible

## Create an account or sign in to comment

You need to be a member in order to leave a comment

## Create an account

Sign up for a new account in our community. It's easy!

Register a new account

• 9
• 12
• 15
• 12
• 24