Karan Bagle
Karan Bagle

Reputation: 29

Why does "print (int('100',2))" give output of 4 in python?

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

Answers (4)

kartoon
kartoon

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

Robert Columbia
Robert Columbia

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

Krishnan Shankar
Krishnan Shankar

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

Midren
Midren

Reputation: 409

100 in binary system is 1*2^2 *0*2^1 + 0 = 4

Upvotes: 3

Related Questions