Can string formatting be used to convert an integer to its binary form ?

Lawrence D'Oliveiro ldo at geek-central.gen.new_zealand
Thu Sep 28 21:07:28 EDT 2006


In message <1159455615.546936.83170 at m7g2000cwm.googlegroups.com>, bearophileHUGS at lycos.com wrote:

> Mirco Wahab:
>> But where is the %b in Python?
> 
> Python doesn't have that. You can convert the number to a hex, and then
> map the hex digitds to binary strings using a dictionary, like this:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440528

How about this: (where n is the integer you want to convert):

    "".join([["0", "1"][(1 << i & n) != 0] for i in range(int(math.ceil(math.log(n, 2))) - 1, -1, -1)])




More information about the Python-list mailing list