Print a string in binary format
Nick Coghlan
ncoghlan at iinet.net.au
Fri Jan 21 09:45:19 EST 2005
neutrino wrote:
> Greetings to the Python gurus,
>
> I have a binary file and wish to see the "raw" content of it. So I open
> it in binary mode, and read one byte at a time to a variable, which
> will be of the string type. Now the problem is how to print the binary
> format of that charater to the standard output. It seems a common task
> but I just cannot find the appropriate method from the documentation.
> Thanks a lot.
>
FWIW, I work with serial data a lot, and I find the following list comprehension
to be a handy output tool for binary data:
print " ".join(["%0.2X" % ord(c) for c in data])
The space between each byte helps keep things from degenerating into a
meaningless mass of numbers, and using 2-digit hex instead of binary works
towards the same purpose. (I actually currently use the hex() builtin, but the
above just occurred to me, and it will give nicer formatting, and avoids the
C-style "0x" prefixing each byte)
Here's an interesting twiddle, though (there's probably already something along
these lines in the cookbook):
Py> def show_base(val, base, min_length = 1):
... chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
... if base < 2: raise ValueError("2 is minimum meaningful base")
... if base > len(chars): raise ValueError("Not enough characters for base")
... new_val = []
... while val:
... val, remainder = divmod(val, base)
... new_val.append(chars[remainder])
... result = "".join(reversed(new_val))
... return ("0" * (min_length - len(result))) + result
...
Py> show_base(10, 2)
'1010'
Py> show_base(10, 2, 8)
'00001010'
Py> show_base(10, 16, 2)
'0A'
Py> show_base(254, 16, 2)
'FE'
Py> show_base(0, 16)
'0'
Py> for base in range(2, 36):
... for testval in range(1000):
... assert testval == int(show_base(testval, base), base)
...
Py>
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at email.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
More information about the Python-list
mailing list