0

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.

Mettepen
  • 61
  • 5
  • 1
    Your hour mapping does not look good if it is supposed to be monotonic. So TIME_7_HOUR should be 1000, 8 should be 1001, 9 1010, 10 1011, 11 1100... – Anty Apr 22 '20 at 09:29
  • If using Windows - Calculator app switched to Programmer calculator is your friend, if you're having difficulty with binary/decimal/hexadecimal/octal conversion. – ChrisBD Apr 22 '20 at 09:42

1 Answers1

2

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;
pmg
  • 106,608
  • 13
  • 126
  • 198
  • Just to add for OP - its important to use unsigned types otherwise bit shift right will leave the top bit set to 1 if it was 1 in order to maintain the sign (unsigned numbers have most significant bit set to 1 to indicate that its negative). – ChrisBD Apr 22 '20 at 09:40