Reputation: 17316
Python 2.6/2.7
I have the following program.
print 0b10
def p_m(x):
print x
p_m(bin(2))
Output:
2
0b10
What I wanted to print in p_m() is 2 (the decimal value) of "0b10" which is what I'm passing to p_m() as first argument and getting this value "0b10" in variable x and just printing that x.
Why print x
inside the function is NOT working like the first line in the program?
What should I do in p_m()'s print statement to print the value of "0b10" as 2.
Upvotes: 2
Views: 6323
Reputation: 12465
print 0b10
gives 2.
This is because all the numbers are stored in python as binary.
bin(2)
is a string. So it gives you the binary value.
You can use print int('0b10', 2)
. Here 2 means the base and '0b10' is the binary you want to convert. 0b
part of 0b10
is not mandatory since int()
already knows it converts it to base 2. Documentation says,
The default base is 10. The allowed values are 0 and 2-36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O/0, or 0x/0X, as with integer literals in code.
Upvotes: 1
Reputation: 8464
Convert the string 0b10
back to int using 2 base parameter:
def p_m(x):
print int(x, 2)
Upvotes: 2
Reputation: 2647
0b10
is an int. bin(2)
is '0b10' which is a string. You'd have to print int('0b10', 2)
to get it to print 2
Upvotes: 2