I wrote a program to solve the exercise below. I got my hours and minutes right, but I cannot get my seconds right.
In order to save disk space Time field in the directory entry is 2 bytes long. Distribution of different bits which account for hours, minutes and seconds is given below:
15 14 13 12 11|10 9 8 7 6 5| 4 3 2 1 0 H H H H H| M M M M M M| S S S S S
Write a C++ Program that take input two-byte time entry and appropriately separates hours, minutes and seconds using suitable bitwise operators.
#include<iostream>
using namespace std;
int main()
{
unsigned int hours, mins, secs;
unsigned int time;
cout << "enter time ";
cin >> time;
hours = (time >> 11);
mins = ((time << 5) >> 10);
secs = ((time << 11) >> 11);
cout << hours << " " << mins << " " << secs << endl;
return 0;
}
To get the minutes, I shift the input to the left by 5 positions, hoping to eliminate all the H
bits, and then shift to the right by 10 positions to eliminate all the S
bits and have the M
bits at the rightmost position.
Similarly for the seconds.
However, if I enter 445
I expect the result to be 13 minutes and 29 seconds, but the program outputs 0 13 445
.
Why do the hours and minutes appear to come out correctly, but not the seconds?