Hexadecimal Conversion in Python

Bengt Richter bokr at oz.net
Wed Nov 2 15:43:34 EST 2005


On 2 Nov 2005 12:53:45 -0800, "DaBeef" <DerrickHaller at gmail.com> wrote:

>I have been coding for 5 years.  This is a proprietary protocol, so it
>is difficult converting.  I did this in java but was just able to
>convert a stream.  I looked through the Python library, I am more or
>less getting backa  string represented as a "...."   So now I want to
>convert it to all the hexa, bin until I see a match and can then work
>teh rest of my program
>
Maybe the binascii module's hexlify will get you into territory more
familiar to you? Python generally stores byte data as type str "strings."
If you want to see the bytes as hex (a string of hex characters ;-) you can e.g.,

 >>> import binascii
 >>> binascii.hexlify('ABC123...\x01\x02\x03')
 '4142433132332e2e2e010203'

To convert individual character, you can use a format string on the ordinal value

 >>> for c in 'ABC123...\x01\x02\x03': print '%02X'%ord(c),
 ...
 41 42 43 31 32 33 2E 2E 2E 01 02 03

Or perhaps you really want the integer ordinal value itself?

 >>> for c in 'ABC123...\x01\x02\x03': print ord(c),
 ...
 65 66 67 49 50 51 46 46 46 1 2 3

(print obviously does a conversion to decimal string representation for output)

If you are interested in the bits, you can check them with bit operations, e.g.,

 >>> for c in 'ABC123...\x01\x02\x03':
 ...     print ''.join(chr(48+((ord(c)>>b)&1)) for b in xrange(7,-1,- 1)),
 ...
 01000001 01000010 01000011 00110001 00110010 00110011 00101110 00101110 00101110 00000001 00000010 00000011

(cf. 41 42 42 etc above)

Regards,
Bengt Richter



More information about the Python-list mailing list