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

Steve Holden steve at holdenweb.com
Fri Sep 29 03:24:32 EDT 2006


MonkeeSage wrote:
> Steve Holden wrote:
> 
>>  >>> to_bin(0)
>>''
> 
> 
> Doh! Oh, yeah...that! ;)
> 
> OK...
> 
> def to_bin(x):
>   out=[]
>   while x > 0:
>     out.insert(0, str(x % 2))
>     x /= 2
>   else:
>     out.append(str(x))
>   return ''.join(out)
> 
It's an often-missed and almost invariably untested corner case that 
one's first attempt to solve the problem usually rids one of. I have 
written binary format code about thirteen times in a lifetime of 
programming so it was easy for me to spot. You'll never make *that* 
mistake again ;-)

Unfortunately forty years of programming experience has taught me that 
there's an essentially infinite supply of mistakes to make ... your 
mistakes just get smarter most of the time.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list