Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

write a program in C that converts decimals to binary. 1. No “magic numbers”, i.

ID: 3744948 • Letter: W

Question

write a program in C that converts decimals to binary.

1. No “magic numbers”, i.e., do not have literal values other than -1, 0, 1 or 2 in your code (use the #define pre-processor directive).

2. It’s ne to have leading 0’s in your output but don’t have “too many”.

3. Group the bits of the output into bytes and all on one line (see the Sample output section).

4. Do not use any user-dened functions, arrays, strings, conditional branches or loops for this program JUST KEEP THINGS SIMPLE!

sample output:

davids@hello$ ./a.out

Enter a valid unsigned short: 139

11010001 00000000

davids@hello$

Explanation / Answer


Given below is the code for the question.
Please do rate the answer if it was helpful. Thank you


#include <stdio.h>
#define NUM_BITS 16
#define BYTE 8
int main()
{
unsigned short decimal;
int i;
unsigned short n, remainder;
printf("Enter a valid unsigned short: ");
scanf("%hu", &decimal);
n = decimal;
for(i = 1;i <= NUM_BITS; i++)
{
remainder = n % 2;
printf("%hu", remainder);
n = n / 2;
if(i % BYTE == 0) //need to print a space after a byte
printf(" ");
}
printf(" ");
}

output
======
Enter a valid unsigned short: 139
11010001 00000000