472,127 Members | 1,627 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,127 software developers and data experts.

how to print out each single char from a string in HEX format?

guys,

I've researched python pretty much but still have no idea how to print
out each single character from a string in HEX format? Hope someone
can give me some hints. Thanks a lot.

e.g. ###here is a string

a='01234'

###how to print out it out in this way

0x31 0x31 0x32 0x33 0x34

Jun 4 '07 #1
4 25341
En Mon, 04 Jun 2007 20:03:39 -0300, mike <ne*********@gmail.comescribió:
I've researched python pretty much but still have no idea how to print
out each single character from a string in HEX format? Hope someone
can give me some hints. Thanks a lot.

e.g. ###here is a string

a='01234'

###how to print out it out in this way

0x31 0x31 0x32 0x33 0x34
pya='01234'
pyfor c in a:
.... print "%#x" % ord(c),
....
0x30 0x31 0x32 0x33 0x34
py>

See <http://docs.python.org/lib/built-in-funcs.html#l2h-55for the ord()
function and <http://docs.python.org/lib/typesseq-strings.htmlfor the
"%#x" format

--
Gabriel Genellina

Jun 4 '07 #2
Great! It works.

Thanks a lot.

Jun 5 '07 #3

Great! It works.
There is a builtin function called hex() that does the same, but also shares
the same problem as the solution above:
>>hex(10)
'0xa'
>>>
This is probably not "nice" in your printouts, it doesn't allign.
with the printf inspired solution you can set the precision like this:
>>a = "12\n34"
for c in a:
.... print "%#04x" % ord(c),
....
0x31 0x32 0x0a 0x33 0x34
>>>

regards troels
Jun 5 '07 #4
On 2007-06-05, Troels Thomsen <nejwrote:
with the printf inspired solution you can set the precision like this:
>>>a = "12\n34"
for c in a:
... print "%#04x" % ord(c),
...
0x31 0x32 0x0a 0x33 0x34
And if you just want to do the conversion w/o printing:
>>a = "12\n34"
>>' '.join(('%#04x' % ord(c) for c in a))
'0x31 0x32 0x0a 0x33 0x34'
>>' '.join(('%02x' % ord(c) for c in a))
'31 32 0a 33 34'

--
Grant Edwards grante Yow! Vote for ME -- I'm
at well-tapered, half-cocked,
visi.com ill-conceived and
TAX-DEFERRED!
Jun 5 '07 #5

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Bob | last post: by
7 posts views Thread by Tommy Vercetti | last post: by
33 posts views Thread by Jordan Tiona | last post: by
8 posts views Thread by Lucky | last post: by
4 posts views Thread by carry | last post: by
5 posts views Thread by Zytan | last post: by
3 posts views Thread by Frank Rizzo | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.