Unpacking a hex value

Peter Hansen peter at engcorp.com
Sat May 18 00:18:14 EDT 2002


Matthew Diephouse wrote:
> 
> 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.

Well, hex() returns a string, not an integer.  The error message is
telling you that an argument to struct.pack() needs to be an integer
but is not.  So why use hex()?

The input to int() must be a decimal integer string, not a hexadecimal 
one, so you get the "invalid literal for int()" message, presumably.  
You could use int(output, 16) instead, which knows about the leading 
"0x" in the string and skips it, or you could just pass the integer 
"input" directly to the pack statement...

I get the impression you are trying to do something slightly 
different than what either of these solutions gives you, so maybe
you could give examples of input and desired output if that doesn't
solve your problems.

> You did get me on the "!l" instead of "l!", but it didn't specify order
> in the struct docs, so I was guessing.

It is a little hard to find, but:

"Alternatively, the first character of the format string can be used 
to indicate the byte order, size and alignment of the packed data, 
according to the following table:" [table snipped]

-Peter



More information about the Python-list mailing list