[Solved] using bitwise operation to extract month from int date (yyyyMMdd)


You could efficiently extract the month with bitwise operations if you represented the date in a binary format, e.g., 5 bits for the day of the month, 4 bits for the month number, and the rest for the year, rather than as decimal digits. For your example, the date would be (2011 << 9) + (4 << 5) + 1 (which of course is not equal to 20110401). To use bitwise operations to extract the fields from such a representation:

int year = date >> 9;
int month = (date >> 5) & 0xF;
int day = date & 0x1F;

Another approach, as mentioned by Mark Byers, is to use a struct, e.g.,

typedef struct {
    short year;
    char  month;
    char  day;
} Date;

You can pass these around on the stack, extract the fields by name, and initialize them as

Date d = { 2011, 4, 1};

or, in C99,

Date d = { .year = 2011, .month = 4, .day = 1 };

solved using bitwise operation to extract month from int date (yyyyMMdd)