How to (quickly) convert float to Byte?

I have a method that processes all the pixels in a bitmap (represented as an array Byte

). For each pixel, I do some pretty complicated calculations for each R, G and B value, using float

to store the calculated value until we finally change it back to Byte

(using only the cast and I'm sure the value in float

will always be 255.0 or less).

While trying to optimize this method, I was surprised to find that about 80% of the total processing time was just dropping the three values float

for R, G and B to their counterparts Byte

.

Is there some super fast way to do this (for example):

float Rtotal = 123.7;
float Gtotal = 7.3;
float Btotal = 221.3;

Byte Rsource = (Byte)Rtotal;
Byte Gsource = (Byte)Gtotal;
Byte Bsource = (Byte)Btotal;

      

+3


source to share


1 answer


Okay, this is a little weird. If I just make this change:

float Rtotal = 123.7;
float Gtotal = 7.3;
float Btotal = 221.3;

Byte Rsource = (int)Rtotal;
Byte Gsource = (int)Gtotal;
Byte Bsource = (int)Btotal;

      



the extra time caused by pressing the key (Byte)

disappears. My guess is that the compiler adds some sort of bounds checking for the cast (Byte)

to make sure it is in the valid byte range, whereas it omits that if the listing matters int

.

+3


source







All Articles