Previous: , Up: Shift Operations   [Contents][Index]


6.7.3 Shift Hacks

You can use the shift operators for various useful hacks. For example, given a date specified by day of the month d, month m, and year y, you can store the entire date in a single integer date:

unsigned int d = 12;		/* 12 in binary is 0b1100.  */
unsigned int m = 6;             /* 6 in binary is 0b110.  */
unsigned int y = 1983;          /* 1983 in binary is 0b11110111111.  */
unsigned int date = (((y << 4) + m) << 5) + d;
                                /* Add 0b11110111111000000000
                                   and 0b11000000 and 0b1100.
                                   Sum is 0b11110111111011001100.  */

To extract the day, month, and year out of date, use a combination of shift and remainder:

/* 32 in binary is 0b100000.  */
/* Remainder dividing by 32 gives lowest 5 bits, 0b1100.  */
d = date % 32;
/* Shifting 5 bits right discards the day, leaving 0b111101111110110.
   Remainder dividing by 16 gives lowest remaining 4 bits, 0b110.  */
m = (date >> 5) % 16;
/* Shifting 9 bits right discards day and month,
   leaving 0b111101111110.  */
y = date >> 9;

-1 << LOWBITS is a clever way to make an integer whose LOWBITS lowest bits are all 0 and the rest are all 1. -(1 << LOWBITS) is equivalent to that, due to associativity of multiplication, since negating a value is equivalent to multiplying it by -1.