Nibin
Nibin

Reputation: 97

Why does converting binary to integer using int() in python gives an error when give 2 as the base argument

I tried the following code,

a=0b1101
b=int(a,2)
print(b)

And it gave me an error.

TypeError: int() can't convert non-string with explicit base

But when I don't mention the base it just works fine,

a=0b1101
b=int(a)
print(b)

Upvotes: 2

Views: 42

Answers (1)

newbiew_alert
newbiew_alert

Reputation: 86

Having zero in the beginning has a special meaning in python. For eg. 0x means hexadecimal number. While using the int() func, we provide the second argument when the binary number is stored in the form of an integer. For eg,

b=int(a,2)

but when converting an actual binary number to integer we don't provide the second argument. Eg,

b=int(a)

Upvotes: 3

Related Questions