Converting Hex to decimal

Holger Türk htx1 at gmx.de
Wed Jun 2 10:23:40 CEST 2004



dean wrote:
> The file is binary. Using the standard hpux or linux hexdump (xxd or
> xd) this is the output that is obtained:
> 
> 0000000: 5c1a 0100 0100 ff35 0399 7272 9903 0002  \......5..rr....
> 0000010: 010e 0300 050a 0214 ffff ffff 5cd4 2e01  ............\...
> 0000020: fbb9 5900 b400 0000 0020 2000 b502 5423  ..Y......  ...T#
> 0000030: 3a71 2e11 00ff ffff ffff ffff ffff ffff  :q..............
> 0000040: ffff ffff ff00 ff07 0209 3519 4fff ffff  ..........5.O...
> 0000050: ffff ffff ffff ffff ffff ffff ffff ffff  ................
> 0000060: ffff ffff ffff ffff ffff ffff ffff ffff  ................
> 0000070: ffff ffff ffff ffff ffff ffff ffff ffff  ................
> 0000080: ffff ffff ffff ff00 5435 3617 040a d207  ........T56.....
> 0000090: 3e05 3717 040a d207 0000 0000 2c01 6000  >.7.........,.`.
> 00000a0: 0141 01a8 0005 030b 0300 00ff ffff ffff  .A..............
> 00000b0: ffff ffff ffff ffff ffff ff00 0000 0000  ................
> 00000c0: 0300 0000 5435 3617 040a d207 0b00 0000  ....T56.........
> 00000d0: 0000 0000 fcb9 5900 b400 0000 0020 2000  ......Y......  .
> 00000e0: b602 5423 3b71 2e11 00ff ffff ffff ffff  ..T#;q..........
> 00000f0: ffff ffff ffff ffff ff00 2094 3965 0702  .......... .9e..
> 0000100: 0935 194f ffff ffff ffff ff07 0209 3519  .5.O..........5.
> 0000110: 4fff ffff ffff ffff ffff ffff ffff ffff  O...............
> 0000120: ffff ffff ffff ffff ffff ffff ffff ffff  ................
> 0000130: ffff ffff ffff ffff ffff ff00 1536 3617  .............66.
> 
> Each hex character is 8 bits. I would like to convert one byte at the
> time and pipe the converted data into a new file.

Ok, you've got the hexdump and, as far as I understand,
you want the binary data back, byte by byte.

import binascii

def makeBinary (f):
     for line in f:
         words = line.split () [1:9]
         for word in words:
             yield binascii.unhexlify (word [:2])
             yield binascii.unhexlify (word [2:])

Then use the generator this way:

for byte in makeBinary (open ("hexdumpfile", "r")):
     [...]

I did not test it, but at least it is an outline of
the way it can be done.

Greetings,

Holger




More information about the Python-list mailing list