943,587 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Unsolved
  • Views: 1867
  • C RSS
Oct 20th, 2008
0

Converting to binary value

Expand Post »
I am trying to convert an int, a char, and a short into their binary values and display it.


int a;
char b;
short c;


I understand how to convert an integer to a binary value bit by bit, I just don't understand how to store it as a varible so I can print it out as a binary value in a printf() line.


do{
int temp = a%2; //the value of the bit starting at the least significant
a = a/2;
//how would i store this bit by bit
}while(a>0);
Last edited by kinger29; Oct 20th, 2008 at 11:41 pm.
Similar Threads
Reputation Points: 11
Solved Threads: 2
Light Poster
kinger29 is offline Offline
35 posts
since Mar 2008
Oct 21st, 2008
0

Re: Converting to binary value

Team Colleague
Reputation Points: 2780
Solved Threads: 312
long time no c
Dave Sinkula is offline Offline
4,790 posts
since Apr 2004
Oct 21st, 2008
0

Re: Converting to binary value

The problem is to print the obtained remainders in the reverse order which implies that you'll have to store some sort of information abt what remainders you obtained in the previous step.

One way to do it is to use a character array as such:
char convert = "01"; Then you can use the remainder obtained as the index to the above string and store the resulting character in another array for later display.
The advantage of the above logic is that you can easily extend your code to make it convert to octal or hexadecimal just by doing: char convert="0123456789ABCDEF" . There recently was a thread which had this program. You can take a look at that.

Another way is to have a multiplier to multiply your obtained remainder with.

code snippet:

  1. while(num>0)
  2. {
  3. temp = num%2; //obtain 0 or 1
  4. temp = mul * temp;// multiply with 1 or 10 or 100...
  5. sum+= temp; // sum holds the final value
  6. mul*=10; // modify mul and num for the next iteration
  7. num/=2;
  8. }
Last edited by devnar; Oct 21st, 2008 at 12:26 am.
Reputation Points: 124
Solved Threads: 18
Junior Poster
devnar is offline Offline
148 posts
since Sep 2008

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: Passing Array Problemmm...
Next Thread in C Forum Timeline: about using data in structure from a text file





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC