UWA Logo Computer Science & Software Engineering
C Programming (CITS1210) - Lecture 12
 
    CITS1210  |  help1210

Storing multiple items in an integer

The most frequently seen example of C's bitwise operators, is the use of the left-shift operator to store multiple "items" in a single integer variable.

Consider the following example, using an unsigned int to represent colours in an RGB format of 24 bits-per-pixel (24bpp):


typedef unsigned int RGBCOLOUR;

RGBCOLOUR set_rgb(char red, char green, char blue)
{
    return (blue << 16) + (green << 8) + red;
}

    ....
    RGBCOLOR white   = set_rgb(255, 255, 255);
    RGBCOLOR black   = set_rgb(  0,   0,   0);
    RGBCOLOR skyblue = set_rgb(135, 206, 235);
    RGBCOLOR yellow  = set_rgb(255, 255,   0);

Here, the left shift operator is used to quickly multiply a small value by a constant power of two.

On most modern architectures, bit-shifting operations are considerably faster than the equivalent multiplications (use left-shifting) and divisions (use right-shifting).


C Programming (CITS1210), Lecture 12, p3, 23rd October 2008.