Write a program to display today\'s date in binary, in this format: Today\'s dat
ID: 3625305 • Letter: W
Question
Write a program to display today's date in binary, in this format:Today's date is:
011
0100
01101
Press any key to continue . . .
The three lines represent, respectively, the day of the week (1-7 for Monday-Sunday), the month of the year (1-12 for January-December), and the day of the month (1-31), all displayed in binary. (The above date is Wednesday, April 13.) You can obtain this information by creating and intializing a pointer to a struct tm, defined in time.h:
/*
* A structure for storing all kinds of useful information
* about the current (or another) time.
*/
struct tm
{
int tm_sec; /* Seconds: 0-59 (K&R says 0-61?) */
int tm_min; /* Minutes: 0-59 */
int tm_hour; /* Hours since midnight: 0-23 */
int tm_mday; /* Day of the month: 1-31 */
int tm_mon; /* Months *since* January: 0-11 */
int tm_year; /* Years since 1900 */
int tm_wday; /* Days since Sunday (0-6) */
int tm_yday; /* Days since Jan. 1: 0-365 */
int tm_isdst; /* +1 Daylight Savings Time, 0 No DST,
-1 don't know */
};
You can declare and initialize a pointer to this structure from the OS clock with this code:
time_t t = time(NULL);
struct tm *st = localtime(&t);
I suggest you get the program working first with a decimal display, then modify it by adding a function that will take an int and construct its binary string equivalent. To convert a decimal integer to binary, one algorithm is to repeatedly divide by two, and the remainders will form the binary number. Here is an example of converting 26_10 to binary. The calculations in the table are carried out from right-to-left (i.e., divide 26 by 2 first).
Number 1 3 6 13 26
Number / 2 0 1 3 6 13
Remainder 1 1 0 1 0
So 26_10 = 11010_2.
Explanation / Answer
please rate - thanks
#include <stdio.h>
#include <conio.h>
#include <time.h>
int tobinary(int);
int main()
{time_t t = time(NULL);
struct tm *st = localtime(&t);
int month,day,dow;
month=st->tm_mon+1;
day=st->tm_mday;
dow=st->tm_wday;
if(dow==0)
dow=1;
printf("Today's date is: %d %d %d ",tobinary(dow),tobinary(month),tobinary(day));
getch();
return 0;
}
int tobinary(int num)
{int digit,answer=0,power=1;
while (num!=0)
{
digit=num%2;
answer=answer+digit*power;
power*=10;
num=num/2;
}
return answer;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.