[Tutor] Applying a mask

Jeff Shannon jeff@ccvcorp.com
Wed, 21 Nov 2001 11:06:01 -0800


>
> On Wed, 21 Nov 2001 08:05:04 -0800,
> Kirby Urner <urnerk@qwest.net> wrote:
>
> At 04:13 PM 11/21/2001 +0100, Felix.Toran@esa.int wrote:
>
> >Dear all,
> >
> >I have a string, containing a 63-digit hexadecimal number.
> >I want to build a function which extracts bits from that
> >hexadecimal number, and show it as an integer (unsigned)
> >value.
>
> The long integer is a place to store big hex numbers.
> In Python 2.2, we're starting to not need to specify
> when an integer is long, with the 'L' suffix.
>
>    >>> myhex = eval('0x'+'A323332BFE23231')
>    >>> myhex
>    734705982275465777L
>
> eval('0x'+yourstring) will need to be written
> eval('0x'+yourstring+'L') if your Python is < 2.2.

A simpler, safer way to do this (in just about any version of Python) is
to use the optional base parameter of the int() built-in function:

>>> num = int('beef',16)
>>> num
48879
>>> hexnum = hex(num)
>>> hexnum
'0xbeef'
>>>

Other than that little detail, Kirby's advice is spot-on...  :)

(Any time you use eval(), there's almost always a better way to do what
you want....)

Jeff Shannon
Technician/Programmer
Credit International