Issue
I have this code so far:
for ( int i = 16; i >=0; i--){
int k = n >> i;
if (k & 1)
printf("1");
else
printf("0");
}
I'm extremely new to C and I'm working on decimal to binary converter for a class. So far this is what I've found that works within my parameters. The only problem is I need this code to ONLY output the binary to the MSD which it was given.
As in if I have the decimal 15 it should display 1111 in binary, and if i have decimal 16 it should display only the next set of 4 above that, so 00010000.
As of right now i can set the amount to whatever i want, as in i = 16, but that would show 15 spaces total. where as if i put in a small decimal i don't want my program to show all the extra unnecessary 0's.
So is there a way to limit the binary output to correspond with say the most significant space necessary to accurately display its conversion?
Solution
One way to do so is to use a flag variable to check if we have a non-zero msb, and start printing 0 only after we encounter a non-zero msb e.g.
int flag
for ( int i = 16; i >=0; i--)
{
int k = n >> i;
if (k & 1){
printf("1");
flag = 1;
}else{
if(flag)
printf("0");
}
Answered By - Sandy Answer Checked By - Marie Seifert (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.