[Mono-list] new color.cs for inclusion in CVS

Brian Crowell brian@fluggo.com
Wed, 6 Mar 2002 18:42:26 -0600


> I think the following would be a nice addition to the following
> function... color.a = ( argpacked & 0xff000000 ) >> 24;
> color.r = ( argpacked & 0xff0000 ) >> 16;
> color.g = ( argpacked & 0xff00 ) >> 8;
> color.b = ( argpacked & 0xff );

Be wary of casts and operators... Your innocent-looking first line does the
following:

 1. Cast argpacked to an Int64, a signed data type capable of holding the
result of the AND.
 2. Cast 0xFF000000 from a UInt32 to an Int64.
 3. Perform the AND.
 4. Perform the shift.
 5. Cast down to a byte.

I've found judicial use of the "unchecked" operator to be helpful. I have a
class that does colors, and it extracts values using code like this:

unchecked
{
	color.a = (byte)(argpacked >> 24);
	color.r = (byte)(argpacked >> 16);
	color.g = (byte)(argpacked >> 8);
	color.b = (byte)(argpacked);
}

This produces very nice IL, and avoids unnecessary casting and overflow
checks.

Also, I see your point about local variables being unassigned. So really,
both cases should be equally optimal. But one's shorter!  :P

--Brian