Code:
#include <stdio.h>
int display_binary(unsigned short number);
int main()
{
unsigned short number;
printf("Enter a whole number between 0 and 65,535: ");
scanf("%hu", &number);
printf("\n\n Decimal: %hu\n", number);
printf("Hexadecimal: %x\n", number);
display_binary(number);
getch();
return 0;
}
int display_binary(unsigned short number)
{
unsigned short mask = 0x8000;
int c, k;
for(c = 0; c < 16; c++)
{
k = (number & mask);
if(k == 0)
printf("0");
else
printf("1");
mask >> 1;
if(c == 3 || c == 7 || c == 11)
printf(" ");
}
}
OK, I know that I am not supposed to just blatantly ask questions for homework, but I can't seem to figure this out... Here is what I was told to do:
Hint: Declare an unsigned short mask = 0x8000 (which is 1000 0000 0000 0000). Write a for loop that iterates 16 times. In each cycle, do a bitwise & between the mask and the input parameter. Display 0 if the outcome is 0 and 1 otherwise. Shift the mask to the right one bit at the end of each cycle to retrieve the next bit in the next cycle. Display a space character after every 4 bits of data to improve readability.
My problem is, that I am getting the binary to be all "1's" for everything I put in. I think I am doing what is instructed, but obviously not.
Thanks in advance for any help,
~Alan