32-Bit Color
To represent a color with 32-bits, a byte is given to each component. Since each color is given an 8-bit byte, we can represent 256 different shades for each color component—0 being no intensity, 255 being full intensity, and intermediate values being intermediate intensities. A byte per color component may seem small, but when we look at all the combinations (256 × 256 × 256 = 16,777,216), we see millions of distinct colors can be represented. The XNA Math library provides the following structure for storing a 32-bit color:
// ARGB Color; 8-8-8-8 bit unsigned normalized integer components packed into a 32 bit integer. The normalized color is packed into 32 bits using 8 bit unsigned, normalized integers for the alpha, red, green, and blue components.The alpha component is stored in the most significant bits and the // blue component in the least significant bits (A8R8G8B8): [32] aaaaaaaa rrrrrrrr gggggggg bbbbbbbb [0]
typedef struct _XMCOLOR
{
union
{
struct
{
UINT b : 8; // Blue: 0/255 to 255/255
UINT g : 8; // Green: 0/255 to 255/255
UINT r : 8; // Red: 0/255 to 255/255
UINT a : 8; // Alpha: 0/255 to 255/255
};
UINT c;
};
#ifdef __cplusplus
_XMCOLOR() {};
_XMCOLOR(UINT Color) : c(Color) {};
_XMCOLOR(FLOAT _r, FLOAT _g, FLOAT _b, FLOAT _a);
_XMCOLOR(CONST FLOAT *pArray);
operator UINT () { return c; }
_XMCOLOR& operator= (CONST _XMCOLOR& Color);
_XMCOLOR& operator= (CONST UINT Color);
#endif // __cplusplus } XMCOLOR;
A 32-bit color can be converted to a 128-bit color by mapping the integer range [0, 255] onto the real-valued interval [0, 1]. This is done by dividing by 255. That is, if 0 ≤ n ≤ 255 is an integer, then gives the intensity in the normalized range from 0 to 1. For example, the 32-bit color (80, 140, 200, 255) becomes On the other hand, a 128-bit color can be converted to a 32-bit color by multiplying each component by 255 and rounding to the nearest integer. For example: (0.3, 0.6, 0.9, 1.0) → (0.3 255, 0.6 255, 0.9 255, 1.0 255) = (77, 153,230, 255)
Additional bit operations must usually be done when converting a 32-bit color to a 128-bit color and conversely because the 8-bit color components are usually packed into a 32-bit integer value (e.g., an unsigned int), as it is in XMCOLOR. The XNA Math library defines the following function which takes a XMCOLOR and returns an XMVECTOR from it:
XMVECTOR XMLoadColor(CONST XMCOLOR* pSource);
The XNA Math library also provides a function to convert an XMVECTOR color to a XMCOLOR: VOID XMStoreColor(XMCOLOR* pDestination, FXMVECTOR V);
Typically, 128-bit colors values are used where many color operations will take place (e.g., in a pixel shader); in this way, we have many bits of accuracy for the calculations so arithmetic error does not accumulate too much. The final pixel color, however, is usually stored in a 32-bit color value in the back buffer; current physical display devices cannot take advantage of the higher resolution color.