Check if input is binary and convert to decimal

  • Thread starter Thread starter remaan
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
5 replies · 2K views
remaan
Messages
132
Reaction score
0

Homework Statement



In this problem I need to check if the input num. from the useer is a binary or Not.
And, then I need to convert this Binary Num. to Decimal.





The Attempt at a Solution



Now, for a number to be a Binary it should only contains 0s and 1s,
should I make an if statement ?
But, even if I make this if it will be so complex, because I have to check that every num. except 0 and 1 does not exist ?

Or, there is a method to check that ?
 
Last edited:
Physics news on Phys.org
you could put the integer into a string then use a for loop to cycle through the array and check to see if the value is above 1. Then you will know if it is binary or not.

you may also want to look at this page http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/
 
Binary numbers are not the only ones that contain only 1s and 0s.

The number 1010101 is a perfectly valid Decimal number.
 
that is true, but even humans cannot distinguish between "1010101" and "ten million one hundred and one thousand and one" in integer form. So there is no way to program that with 0% error unless you ask the user if the input is a binnary number or an integer.
 
Thanks a lot!

I will check this =)
 
That is right.
A number with just ones and zeros can occur in a string of decimal numbers.

You can work out the odds of this happening.
Each digit has to be a 1 or a zero and not a number between 2 and 9, inclusive.

So there is a 20% chance of this happening once, a 4 % chance of it happening twice and so on.
If you took the first 10 digits and they were all 0s or 1s the odds against this happening randomly in a decimal number would be nearly 10 million to 1.

To be 100% sure, though, the data should be tagged with some marker that it is binary.
It is traditional to use the percent sign as a tag to indicate binary. So, you would say %11111 = 31