Python question: string of binary to an actual binary number

Status
Not open for further replies.

Desrib

Seniorius Lurkius
8
I have a string of 1s and 0s that represents a binary number (e.g. '00101101'). How would I convert that to an actual num? If I use int(), Python assumes decimal and creates a number that's much, much bigger (in the above example, it would return the # 101101 instead of 45). I tried the binascii.a2b_uu(string) function, but I got a trailing garbage error, and I couldn't figure out what that means. Anybody know of a quick fix that I'm missing?
 

Jonathon

Ars Legatus Legionis
17,646
Subscriptor
int("10011101", base=2)

None of the binascii functions do what you're trying to do. (That module is focused around decoding blocks of data encoded in various schemes that would take arbitrary binary data and encode them using subsets of the ASCII character set, to allow files to be transmitted over protocols which were only designed for text, like email or newsgroups.)
 
[url=http:/civis/viewtopic.php?p=25989621#p25989621:2t5cjbir said:
Jonathon[/url]":2t5cjbir]int("10011101", base=2)

This will serve only to acknowledge my lack of Python knowledge (I've completed ~50 project euler questions using Python but that's about all I've used it for), but that is really cool and may actually be faster than googling when I need a quick conversion between bases.
 

Jonathon

Ars Legatus Legionis
17,646
Subscriptor
[url=http:/civis/viewtopic.php?p=25990773#p25990773:k1pikimv said:
ledbutter[/url]":k1pikimv]
[url=http:/civis/viewtopic.php?p=25989621#p25989621:k1pikimv said:
Jonathon[/url]":k1pikimv]int("10011101", base=2)

This will serve only to acknowledge my lack of Python knowledge (I've completed ~50 project euler questions using Python but that's about all I've used it for), but that is really cool and may actually be faster than googling when I need a quick conversion between bases.
Python makes a pretty nice interactive calculator.

You can do the other way around, too, with the builtin function bin(x). (And there are also hex() and oct() builtins, if you also need to go back and forth between base 16- or base 8-represented strings and ints). Oddly (considering Python's "include all the things!" mentality), there actually isn't a succinct inverse to int(x, base) which will take an int and output a string of an arbitrary base (so, if for some strange reason you're trying to do base 5 math in python, you'll have to do a bit more work to convert into a base 5 string).
 
Status
Not open for further replies.