-1

I'm trying to get toBase10(101) to spit out 5. I also need it to work for numbers besides 101, I know that there is a binary converter built into python but I can't figure it out.

Right now I have

def toBase10(x):
    int( 'x' , 2 ) == x
    return x

I get the error can't convert non-string with explicit base. Why can't I use x in here?

user1719045
  • 1
  • 1
  • 4
  • 2
    Welcome to Stack Overflow! Your question is most probably a duplicate of: [How do you express binary literals in Python?](http://stackoverflow.com/questions/1476/how-do-you-express-binary-literals-in-python) – Pedro Romano Nov 09 '12 at 21:28

3 Answers3

0
def toBase10(x):
    return int(x, 2)
Brigham
  • 14,395
  • 3
  • 38
  • 48
0

I converted the integer into a string and then into binary with which I could easily convert into an integer:

def binaryconvert(x): 
    x = str(x) 
    binarynumber = int(x, base=2)
    convertnumber = int(binarynumber)
return convertnumber

print(binaryconvert(101))
#the answer would be 5

There's also another way if your input is already binary:

def binaryconvert(x):
    convertnumber = int(x)
    return convertnumber

x = int(input("Input: "),2)
print(binaryconvert(x))
SherylHohman
  • 16,580
  • 17
  • 88
  • 94
  • Welcome. Please review topics at StackOverflow.com/help before your next post. Grammar & spelling are important. Refrain from excuses, & clutter such as please/help/thanks. Good answers are always welcome. Most upvotes are accrued over time as future visitors learn something from your post to apply to their own coding issues. It's place to learn & share. If you see a duplicate question, flag it as such. Rem: explanations are always encouraged, & docs links are welcome (but *always embed* necessary info from the link, too.) Looking forward to your insights. – SherylHohman Apr 06 '21 at 03:58
-1

try

def toBase10(item):
     return int(str(item),2)

then you can pass either string or int

    print toBase10(101)
    print toBase10('101')

i think the int cast error is because you are passing in a number not a string, although this looks odd --> "int( x , 2 ) == x" too

vurentjie
  • 106
  • 1
  • 5