# Help with digits

• 10-03-2007
jrice528
Help with digits
Write a program that reads in an unsigned integer containing only 0s and 1s (i.e. a "binary" integer) and outputs its decimal equivalent. Use the modulus and division operators to pick off the "binary" number's digits one at a time from rigiht to left. Much as in the decimal number system, where the rightmost digit has a positional value of 1 (=100), the next digit left has a positional value of 10 (=101), then 100 (=102), then 1000 (=103), and so on, in the binary number system the rightmost digit has a positional value of 1 (=20), the next digit left has a positional value of 2 (=21), then 4 (=22), then 8 (=23), and so on. Thus, the decimal number 234 can be interpreted as 2*100 + 3*10 + 4*1.

Your program must accept only (unsigned) "binary"integers containing only 0s and 1s. Do not read in the integer as a string object. Use a loop to validate the input: the user should get stuck entering a "binary" integer if the value entered is not of the right form.

I don't understand how to start the program off using the modulus and division operators to seperate the number into digits. Does anybody have any suggestions? I just started programming and this is my first assignment.
• 10-03-2007
hk_mp5kpdw
Code:

```int value = 12345; while( value > 0 ) {     cout << value &#37; 10 << endl;     value /= 10; }```
Should output:
Code:

```5 4 3 2 1```
• 10-03-2007
jrice528
I have it to where I can enter my int.

What kind of statement would I use to, take that digit, and to check to see if it is <2, then give it a power to turn it into decimal form.
• 10-03-2007
Desolation
Quote:

What kind of statement would I use to, take that digit, and to check to see if it is <2, then give it a power to turn it into decimal form.
Quote:

Originally Posted by hk_mp5kpdw
Code:

```int value = 12345; while( value > 0 ) {     cout << value % 10 << endl;     value /= 10; }```
Should output:
Code:

```5 4 3 2 1```

*cough*

Did you even read the first reply ?
• 10-03-2007
hk_mp5kpdw
You need something to hold a sum and a counter initialized to 0. In the loop, once you've got the particular digit you are dealing with in the current iteration of the loop, you add to the sum an amount equal to the current digit (which will always be either a 1 or a 0) times 2 raised to the power which is currently stored in the counter. You can use the pow function for that. Towards the end of the loop, you can increment counter by 1.

To do the validation, just loop through and check if each digit is either a 0 or a 1.