print format for binary representation

R

Rim

Hi,
Traceback (most recent call last):

No formating string for binary? There %x for hex. Would %b make sense
for bin? Is this worth a PEP?

How do I get 00110110 printed instead of the traceback?

Thanks,
-Rim
 
J

Jp Calderone

Hi,

Traceback (most recent call last):


No formating string for binary? There %x for hex. Would %b make sense
for bin? Is this worth a PEP?

How do I get 00110110 printed instead of the traceback?

Oft requested, oft rejected. Defining binary() is about one line of code.
Hex is supported because printf(3) supports it.

Here's a version to toy with:

binary = lambda i, c = (lambda i, c: i and (c(i >> 1, c) + str(i & 1)) or ''): c(i, c)

Jp
 
G

Guest

Here's a version to toy with:
binary = lambda i, c = (lambda i, c: i and (c(i >> 1, c) + str(i & 1))
or ''): c(i, c)

Is this example in perl or python?

My brain hurts!

:)
 
D

Dan Bishop

Hi,

Traceback (most recent call last):


No formating string for binary? There %x for hex. Would %b make sense
for bin? Is this worth a PEP?

Yes, it would. No, it isn't.

What we really need is an inverse to the int constructor. Something like:

def itoa(x, base=10):
isNegative = x < 0
if isNegative:
x = -x
digits = []
while x > 0:
x, lastDigit = divmod(x, base)
digits.append('0123456789abcdefghijklmnopqrstuvwxyz'[lastDigit])
if isNegative:
digits.append('-')
digits.reverse()
return ''.join(digits)
How do I get 00110110 printed instead of the traceback?

print itoa(54, 2).zfill(8)
 

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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top