Search⌘ K
AI Features

Solution: Convert 2-Bytes Time Into Hours, Minutes, and Seconds

Explore how to convert a 2-byte encoded time value into hours, minutes, and seconds using bitwise shifts in C. Understand the extraction of specific bits for hours, minutes, and seconds to accurately decode compact time data for efficient programming.

We'll cover the following...

Solution

RUN the code given below and see its output!

C
# include <stdio.h>
void displayTime ( unsigned short int time ) ;
int main( )
{
unsigned short int time ;
time = 10000 ;
displayTime ( time ) ;
return 0 ;
}
void displayTime ( unsigned short int tm )
{
// Declare variables
unsigned short int hours, minutes, seconds, temp ;
// Extract hours
hours = tm >> 11 ;
// Extract minutes
temp = tm << 5 ;
minutes = temp >> 10 ;
// Extract seconds
temp = tm << 11 ;
seconds = ( temp >> 11 ) * 2 ;
// Display hours minutes and seconds
printf ( "For Time = %hu\n", tm ) ;
printf ( "Hours = %hu\n", hours ) ;
printf ( "Minutes = %hu\n", minutes ) ;
printf ( "Seconds = %hu\n", seconds ) ;
}

Explanation

The program given above converts 10000 into 4:56:32. To carry out the conversion, the << and >> operators are suitably used as shown in the code. In this 2-byte number, the leftmost 5 bits ...