manipulating hex values

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Apr 1 20:04:55 CEST 2008


En Tue, 01 Apr 2008 14:11:31 -0300, Stephen Cattaneo  
<stephen.cattaneo at u4eatech.com> escribió:

> I am relatively new to socket programming.  I am attempting to use raw
> sockets to spoof my IP address.

Don't bother to try...

> From what I can tell I will have to
> build from the Ethernet layer on up.   This is fine, but I am having
> some trouble with manipulating my hex values.
>
>  Seems to me that there are two ways to store hex values:
> 1. as literal hex - 0x55aa
> 2. as a string - "\x55aa"

The later is exactly the same string as "Uaa":

py> print "\x55aa"
Uaa

> If I want to convert hex to decimal I can use:
> int("\x55aa", 16)  # note that plain 0x55aa, instead of "\x55aa", will
> raise an exception

Have you tried it?

py> int("\x55aa", 16)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 16: 'Uaa'
py> int("0x55aa", 16)
21930

> The Question:
> If I want to do any kind of calculation I have found its best to just
> convert my values to decimal, do the math, then convert back to hex.  In
> my bellow code I get

"decimal" and "hex" are just ways to represent/display integers. You  
convert from the representation used on the source, to integer, do some  
math, and convert again to another representation for display/store the  
result.

> """byteList.append(int(value,16))
> ValueError: invalid literal for int()"""
> when attempting to run.   I do not understand why this exception is
> being raised?  It is a for loop iterating over a list of hex strings.
> Sorry for the long-ish question.  Any help or comments would be  
> appreciated.

Use the struct package.

-- 
Gabriel Genellina




More information about the Python-list mailing list