Search code examples
cbit-manipulationansi-c

Dummies guide to bit shifting?


I'm currently in C course and we are working on bitshifting to pack a date. I understand the concept of shifting but I am at a loss for the rudimentary stuff like how many places to shift and how to formulate the mask, so I can pull them back out. Any direction or recommended reading would be great.

I've got this far :-(

 #define DAY_MASK  0x???

 #define DAY_OFFSET  ?

 #define MONTH_MASK  0x???

 #define MONTH_OFFSET  ?

 #define YEAR_MASK  0x???

 #define YEAR_OFFSET  ?

Thanks


Solution

  • Assume you want 5 bits to days, 4 bits to month, and all the rest to year, something like:

    #define DAY_OFFSET 0
    #define MONTH_OFFSET 5
    #define YEAR_OFFSET 9
    #define DAY_MASK 0x1F
    #define MONTH_MASK 0x1E0
    #define YEAR_MASK (~0x1FF)
    

    note that I use the ~ operator in year, so it will work on any machine (with no care to the size of int except that it should be large enough to contain the date)

    edit: If you (like me) feel not natural with hex numbers, you can use binary:

    #define DAY_MASK 0b11111
    #define MONTH_MASK 0b111100000
    #define YEAR_MASK (~0b111111111)
    

    and then you can clearly see which bits every field use.