Reputation: 29
Hello I was trying to solve some code and I am stuck in this, I don't have any idea why print(int('100',2))
outputs 4, please explain it to me.
Upvotes: 2
Views: 4596
Reputation: 1194
The int()
function converts the specified value into an integer number.
int(x, base=10)
base
is optional and is set default to 10.
100 (in base 2, i.e. binary) is 4 (in base 10, i.e. decimal)
Upvotes: 2
Reputation: 6418
The int(x,base) function converts a number from a specified base to a decimal integer. 100 in base 2 is 4 in base 10.
Similarly, if you run print(int('10'),2))
, you will get 2
, since 10
in binary is equal to 2
in decimal.
Upvotes: 1
Reputation: 940
When you call int()
, you are giving it two parameters: '100'
, and 2
. The first parameter it takes is the number as a string, and the second is the base. So, you are telling it to convert the string '100'
into an integer of base 2. 100 in base 2 is four, so you are getting this output. Hope this helps!
Upvotes: 3