Unpacking a hex value
Bengt Richter
bokr at oz.net
Sat May 18 05:08:29 EDT 2002
On Sat, 18 May 2002 02:36:51 GMT, Matthew Diephouse <fokke_wulf at hotmail.com> wrote:
>The code is very much like the Perl code I submitted. It is within a
>subroutine.
>
>def hex2bin(input)
> output = hex( input )
> output = pack("!l", output)
> ...
>
> From this, I get the error "required argument is not an integer", as
>previously stated. There's no other info in the Traceback that's
>important. I've tried wrapping output with a call to the int() function,
>but that doesn't work either.
>
>You did get me on the "!l" instead of "l!", but it didn't specify order
>in the struct docs, so I was guessing.
>
Notice that hex in perl and python effectively are inverses of each other:
[ 1:47] C:\pywk>python -c "print hex(65539)"
0x10003
[ 1:47] C:\pywk>perl -e "print hex('0x10003')"
65539
So if I understand right I would guess you need something like
>>> from struct import pack
>>> def hex2bin(input):
... output = int( input, 16) # makes 32-bit native int from hex string
... output = pack("!l", output) # takes native int and packs its bytes into 'network' order string
... return output
...
>>> hex2bin('12345678')
'\x124Vx'
>>> ['%02X' % ord(x) for x in hex2bin('12345678')] # hex values of char seq generated
['12', '34', '56', '78']
Which you can see is the hex values of the characters of the above '\x124Vx' in order,
appropriate for stuffing a big-endian long to get the same numeric value:
>>> [chr(int(x,16),) for x in ['12', '34', '56', '78']]
['\x12', '4', 'V', 'x']
Note that this is on NT/Pentium, so if we leave out the network '!' we get little endianness:
>>> def hex2bin(input):
... output = int( input, 16)
... output = pack("l", output)
... return output
...
>>> hex2bin('12345678')
'xV4\x12'
>>> ['%02X' % ord(x) for x in hex2bin('12345678')]
['78', '56', '34', '12']
>>> [chr(int(x,16),) for x in ['78', '56', '34', '12']]
['x', 'V', '4', '\x12']
Regards,
Bengt Richter
More information about the Python-list
mailing list