Reputation: 1495
I am trying to use the int(x, base) class functionality using Python 2.7
when I do:
num = int('100', 2)
I receive the answer 4
however, when I do num = int('72', 2)
I get the following traceback.
Traceback (most recent call last):
File "foobar1.py", line 26, in <module>
num = int('72', 4)
ValueError: invalid literal for int() with base 4: '72'
I'm not sure what I'm missing.
Upvotes: 0
Views: 1267
Reputation: 3756
The base number is specifying the numeric base of the value. For example, setting base to 16 means you are working with a hexadecimal number, while setting it to 8 means you are working with numbers in octal.
In octal (base 8), the digits available to you are 0--7. Trying to convert the number '89' using the function num = int('89', 8) will give you an error because the digits 8 and 9 are not used in base 8 numbers. Similarly, in base 2, the only digits available to you are 0 and 1 - the highest digit allowed will be the base number - 1.
Hopefully this clears things up.
Upvotes: 1
Reputation: 521
Second parameter means base. Base 2 means the number can use only 2 numbers (which are 0 and 1). When you are trying to convert 72 from binary (base 2) it fails because numbers 7 and 2 do not exist in binary.
If you are trying to convert your number to binary, use bin()
Upvotes: 1
Reputation: 25908
72
is not a binary number (at a minimum it's base 8), but when you specify a base of 2
, you assert that it is. So your function fails.
num = int('1001000', 2)
or:
num = int('1020', 4)
would work as expected, for instance, and give you an integer that will be equivalent to decimal 72
.
Upvotes: 1