PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 12, 2022

[FIXED] how do i limit the binary displayed in my decimal to binary converter?

 August 12, 2022     binary, c, converters, decimal     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing