You are invited to Log in or Register a free Frihost Account!

C++ help

carl005
I'm taking a programming class at school. I'm supposed to convert a base ten tumber between 0-255 to binary. I'm supposed to use a while loop and it has something to do with remainders (something to do with % or mod). I've been sick so I haven't really been able to ask my teacher for help. I was wondering if anyone could offer me some advice. Thank you to anyone who can help.
SystemWisdom
First step would be to find a suitable algorithm for your purposes.. Converting decimal to binary is a simple task, and the math behind it is relatively simple (even for me)... But if you don't have one, here is a simple pseudo-code algorithm.. see if you can code this into your C++ program..

 Quote: 1. Let D= the number we wish to convert from decimal to binary. 2. Repeat until D=0: a) If D is odd, put "1" in the leftmost open column, and subtract 1 from D. b) If D is even, put "0" in the leftmost open column. c) Divide D by 2. End Repeat Proof: For the number 163, this works as follows: 1. Let D=163 2. b) D is odd, put a 1 in the 2^0 column. Subtract 1 from D to get 162. c) Divide D=162 by 2. Temporary Result: 01 New D=81 D does not equal 0, so we repeat step 2. 2. b) D is odd, put a 1 in the 2^1 column. Subtract 1 from D to get 80. c) Divide D=80 by 2. Temporary Result: 11 New D=40 D does not equal 0, so we repeat step 2. 2. b) D is even, put a 0 in the 2^2 column. c) Divide D by 2. Temporary Result:011 New D=20 2. b) D is even, put a 0 in the 2^3 column. c) Divide D by 2. Temporary Result: 0011 New D=10 2. b) D is even, put a 0 in the 2^4 column. c) Divide D by 2. Temporary Result: 00011 New D=5 2. a) D is odd, put a 1 in the 2^5 column. Subtract 1 from D to get 4. c) Divide D by 2. Temporary Result: 100011 New D=2 2. b) D is even, put a 0 in the 2^6 column. c) Divide D by 2. Temporary Result: 0100011 New D=1 2. a) D is odd, put a 1 in the 27 column. Subtract 1 from D to get D=0. c) Divide D by 2. Temporary Result: 10100011 New D=0 D=0, so we are done, and the decimal number 163 is equivalent to the binary number 10100011. Since we already knew how to convert from binary to decimal, we can easily verify our result. 10100011=(1*2^0)+(1*2^1)+(1*2^5)+(1*2^7)=1+2+32+128= 163.

This quote was taken from: http://www.math.grin.edu/~rebelsky/Courses/152/97F/Readings/student-binary.html

I hope that helps.. And if you can't seem to get it, let us know, and I (or someone else) will code a sample for you..
carl005
awesome, that helps a lot.
thank you!