Can string formatting be used to convert an integer to its binaryform ?

G

George Sakkis

Steve said:
MonkeeSage said:
So far as unobfuscated versions go, how about the simple:

def to_bin(x):
out = []
while x > 0:
out.insert(0, str(x % 2))
x = x / 2
return ''.join(out)

Regards,
Jordan
to_bin(0)
''

6/10: try harder :)

Ok, how about a fast *and* readable version? Works for non-negatives,
but negatives are trivial to add if necessary:

from array import array

def fast2bin(n):
s = array('c')
while n>0:
s.append('01'[n&1])
n >>= 1
s.reverse()
return s.tostring() or '0'

try: import psyco
except ImportError: pass
else: psyco.bind(fast2bin)


George
 
M

MonkeeSage

Steve said:

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)

Regards,
Jordan
 
S

Steve Holden

MonkeeSage said:
Steve said:


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
 
F

Frederic Rentsch

Frederic Rentsch:


Note that your version keeps the leading zeros.
Have you tested the relative speeds too?
(I'll probably have to learn to use SE.)

Bye,
bearophile
If you say speed, I presume you mean speed of execution. No I have not
tested that. I know it can't be fast on a test bench. After all, SE is
written in Python. I did a first version fifteen years ago in C, am
still using it today on occasion and it runs much, much faster than this
Python SE. This SE here could be done in C if it passes the test of
acceptance.
Professionals need to measure execution speed as a part of
documenting their products. I am not a professional and so I am free to
define my own scale of grades: A (fast enough) and F (not fast enough).
I have yet to encounter a situation where SE gets an F. But that says
less about SE than about my better knowledge which prevents me from
using SE to, say, change colors in a 50 Mb bitmap. Obviously, "fast
enough" and "not fast enough" pertains not to code per se, but to code
in a specific situation. So, as the saying goes: the proof of the
pudding ...
Another kind of speed is production speed. I do believe that SE
rather excels on that side. I also believe that the two kinds of speed
are economically related by the return-on-investment principle.
The third kind of speed is learning speed. SE is so simple that it
has no technical learning curve to speak of. It's versatility comes from
a wealth of application techniques that invite exploration, invention
even. Take leading zeroes:

Leading zeroes can be stripped in a second pass if they are made
recognizable in the first pass by some leading mark that is not a zero
or a one. ([^01]; I use "@" in the following example). To purists this
may seem hackish. So it is! And what's wrong with that if it leads to
simpler solutions?
6=0110 7=0111 8=1000 9=1001 A=1010 a=1010 B=1011 b=1011 C=1100 c=1100
D=1101 d=1101 E=1110 e=1110 F=1111 f=1111 | ~[^01]0*~=')
.... snip ...

Data Chain
----------------------------------------------------------------------------------
@499602d2
0
--------------------------------------------------------------------------------
@01001001100101100000001011010010
1
--------------------------------------------------------------------------------
1001001100101100000001011010010
----------------------------------------------------------------------------------


Frederic

(The previously posted example "Int_To_Binary = SE.SE (SE.SE ( ..." was
a typo, or course. One (SE.SE does it. Sorry about that.)
 
S

Simon Brunning

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.

+1 QOTW.
 
N

Neil Cerutti

MonkeeSage said:
So far as unobfuscated versions go, how about the simple:

def to_bin(x):
out = []
while x > 0:
out.insert(0, str(x % 2))
x = x / 2
return ''.join(out)

Regards,

It was surprising that

is a one-way operation.
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: str() takes at most 1 argument (2 given)
 
G

Georg Brandl

Neil said:
MonkeeSage said:
So far as unobfuscated versions go, how about the simple:

def to_bin(x):
out = []
while x > 0:
out.insert(0, str(x % 2))
x = x / 2
return ''.join(out)

Regards,

It was surprising that

is a one-way operation.
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: str() takes at most 1 argument (2 given)

str() is not only for converting integers, but all other types too.
An explicit argument for this special case is not Pythonic IMO.

Georg
 
N

Neil Cerutti

Neil said:
MonkeeSage wrote:
So far as unobfuscated versions go, how about the simple:

def to_bin(x):
out = []
while x > 0:
out.insert(0, str(x % 2))
x = x / 2
return ''.join(out)

Regards,

It was surprising that
i = int("111010101", 2)

is a one-way operation.
s = str(i, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: str() takes at most 1 argument (2 given)

str() is not only for converting integers, but all other types
too. An explicit argument for this special case is not Pythonic
IMO.

I suppose two wrongs wouldn't make a right. ;)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top