By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,797 Members | 1,251 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,797 IT Pros & Developers. It's quick & easy.

print format for binary representation

P: n/a
Rim
Hi,
print '%x' % 54 36 print '%b' % 54 Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: unsupported format character 'b' (0x62) at index 1


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
Jul 18 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
On Tue, Jan 27, 2004 at 07:00:23AM -0800, Rim wrote:
Hi,
print '%x' % 54 36 print '%b' % 54 Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: unsupported format character 'b' (0x62) at index 1


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
Jul 18 '05 #2

P: n/a
> 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!

:-)


Jul 18 '05 #3

P: n/a
ri*******@yahoo.com (Rim) wrote in message news:<6f**************************@posting.google. com>...
Hi,
print '%x' % 54 36 print '%b' % 54 Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: unsupported format character 'b' (0x62) at index 1

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('0123456789abcdefghijklmnopqrstuvwxy z'[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)
Jul 18 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.