Weird 'and' result...

Bengt Richter bokr at oz.net
Sat Jun 21 02:34:14 CEST 2003


On Fri, 20 Jun 2003 23:22:46 +0000 (UTC), "Artur M. Piwko" <pipen at beast_tu_kielce.pl> wrote:

>pipen at demon:/tmp/ekg-1.1rc1$ python
>Python 2.2.3 (#1, Jun  4 2003, 02:54:59)
>[GCC 3.3 (Debian)] on linux2
>Type "help", "copyright", "credits" or "license" for more information.
>>>> "%08x" % (0xea7ee5ccea7 & 0xffffffff)
>'ea7ee5ccea7'
>>>>
>
>And it should be 'ee5ccea7'. Am I missing something?
>
 >>> 0xea7ee5ccea7
 16114421386919L
 >>> 0xffffffff
 -1
 >>> 0xffffffff +0L
 -1L
 >>> 0xffffffffL
 4294967295L
 >>> "%08x" % (0xea7ee5ccea7 & 0xffffffffL)
 'ee5ccea7'

It's a problem with the traditional hex literal representation of int numbers, which are
usually 32 bits, and so wind up signed if the 0x80000000 bit is set. When an operation with
a long causes promotion of the int to long, the sign bit gets logically extended, so it's
as if you had all f's still.

You can append an L as above to get the 0-sign-extended mask.

Btw, a literal format of 1x... for 1s and 0x... 0s as sign extensions has been proposed,
which I like much better than putting a '-' in front of the hex for the absolute value.
IOW, I'd rather write 1xa than -0x6, which doesn't show me the bits I'm used to.

 >>> hex(-0x6)
 '0xfffffffa'
 >>> hex(-0x6L)
 '-0x6L'

The bits are there, you just don't get to see them 'normally' in the hex representation of
negative longs.
 >>> hex(-0x6L & 0xffff)
 '0xFFFAL'

whereas you could with the 1xa == 1xfa == 1xffffffa format.

Regards,
Bengt Richter




More information about the Python-list mailing list