unsigned integers

Jp Calderone exarkun at intarweb.us
Thu Mar 6 14:23:10 EST 2003


On Thu, Mar 06, 2003 at 02:35:13PM +0000, Giovanni Bajo wrote:
> Hello,
> 
> I have some troubles with signed/unsigned integers, probably because it is
> still not clear to me how Python works with respect to this. Especially:
> 

  Python doesn't have unsigned ints builtin.

> 1) How can I force 0xFFFFFFFF to be 4294967295 instead of -1? My problem is
> that I'm converting some C code like a = b*c where the result needs to be
> wrapped within 32-bit limits. If I bit-and the result with 4294967295
> everything is ok, but if I use 0xFFFFFFFF the number does not mask
> correctly, because 0xFFFFFFFF is seen as -1. Why should it ever consider a
> hex literal as negative, by the way? Is there any real-world case where this
> is needed?
> 

  Python ints (on 32 bit platforms) use 31 bits for value and one bit for
sign, so you can't have 2**32-1 as an int, you'll need a long.  This is easy
- 0xFFFFFFFFL or long('FFFFFFFF', 16) (and in 2.3, int('FFFFFFFF', 16) will
work, too).

  That said, -1 and 0xFFFFFFFF are really the same thing.  The bits of -1
are all set so, if I understand what you're trying to do, using -1 will work
fine.


> 2) binascii.crc32() returns a signed integer representing the CRC. I call it
> signed because if I print the result it displays a signed number. Now, what
> if I need the unsigned representation of it (as in, the unsigned number
> which is machine-represented with the same 32 bits)? I need to multiply it
> by another integer, but I need an unsigned multiplication, not a signed one.
> 

  This works:

    >>> import struct
    >>> struct.unpack('!L', struct.pack('!l', -3))
    (4294967293L,)

  See the struct module docs for why.

  Jp

-- 
 up 3 days, 11:58, 7 users, load average: 0.12, 0.20, 0.18





More information about the Python-list mailing list