Search code examples
cbit-manipulationbitmaskbyte-shifting

How to do bitmanipulation with more values without multiple masks?


I have this assignment and I am not sure how to do this and a simple google wouldn't help me. Also not exactly sure what to search for.

But I'm creating a clock / watch that contains hours, minutes and seconds. And the bitmask I'm given to use is:

0000 0000 mask1
hhhh mmmm
0000 0000 mask2
mmss ssss

What I understood so far is that the amount of Hour bits is the reason to fit 12 options from 0 -> 11. And the 6 bits for minutes and seconds for 0 -> 59.

For hours I kindof went in the dark creating 12 seperate bitmasks for each possible hour. After I finished I realized I had to do this for minutes and seconds as well which would be 120 lines of unneccessary code.

This is what I did:

  TIME_11_HOUR = 240, //1111
  TIME_10_HOUR = 224, //1110
  TIME_9_HOUR = 192,  //1100
  TIME_8_HOUR = 160,  //1010
  TIME_7_HOUR = 144,  //1001
  TIME_6_HOUR = 112,  //0111
  TIME_5_HOUR = 96,   //0110
  TIME_4_HOUR = 80,   //0101
  TIME_3_HOUR = 64,   //0100
  TIME_2_HOUR = 48,   //0011
  TIME_1_HOUR = 32,   //0010
  TIME_0_HOUR = 16    //0001 0000

I believe the solution has to do with bit shifting but im not really sure how to do that.

Could anyone give me an example to change 0001 (0 hour) to 1010 (8 hour) so I can implement this in my code and figure it out on my own.


Solution

  • assuming all values are within range and using unsigned types...

    to unencode

    hour = (encodedtime & 0xf000) >> 12;
    minute = (encodedtime & 0xfc0) >> 6;
    second = encodedtime & 0x3f;
    

    to encode

    encodedtime = (hour << 12) | (minute << 6) | second;