Weird 'and' result...

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

On Fri, 20 Jun 2003 23:22:46 +0000 (UTC), "Artur M. Piwko" <pipen at> 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)
>And it should be 'ee5ccea7'. Am I missing something?
 >>> 0xea7ee5ccea7
 >>> 0xffffffff
 >>> 0xffffffff +0L
 >>> 0xffffffffL
 >>> "%08x" % (0xea7ee5ccea7 & 0xffffffffL)

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)
 >>> hex(-0x6L)

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

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

Bengt Richter

More information about the Python-list mailing list