I'm using Python 3.2.2.
I'm looking for a function that converts a binary string, e.g. '0b1010' or '1010', into a binary literal, e.g. 0b1010 (not a string or a decimal integer literal).
It's an easy matter to roll-my-own, but I prefer to use either a standard function or one that is well-established: I don't want to 're-invent the wheel.'
Regardless, I'm happy look at any efficient algorithms y'all might have.
2 Answers 2
The string is a literal.
3>> bin(int('0b1010', 2))
'0b1010'
3>> bin(int('1010', 2))
'0b1010'
3>> 0b1010
10
3>> int('0b1010', 2)
10
7 Comments
print('0b1010')?Try the following code:
#!python3
def fn(s, base=10):
prefix = s[0:2]
if prefix == '0x':
base = 16
elif prefix == '0b':
base = 2
return bin(int(s, base))
print(fn('15'))
print(fn('0xF'))
print(fn('0b1111'))
If you are sure you have s = "'0b010111'" and you only want to get 010111, then you can just slice the middle like:
s = s[2:-1]
i.e. from index 2 to the one before the last.
But as Ignacio and Antti wrote, numbers are abstract. The 0b11 is one of the string representations of the number 3 the same ways as 3 is another string representation of the number 3.
The repr() always returns a string. The only thing that can be done with the repr result is to strip the apostrophes -- because the repr adds the apostrophes to the string representation to emphasize it is the string representation. If you want a binary representation of a number (as a string without apostrophes) then bin() is the ultimate answer.
2 Comments
0b1 ^ 0b10 but not '0b1' ^ '0b10', and using bin doesn't change this.bin() returns a string representation as a binary number. When doing the exclusive or operation, you want to keep it as an abstract number. For that case, you simply remove the bin wrapper at the return line (but this was not the question). Or you can write a function that implements the xor operation on string representation of bits.