Bit-twiddling

Tamito Kajiyama kajiyama at grad.sccs.chukyo-u.ac.jp
Wed Jul 28 21:37:04 EDT 1999


Lars Marius Garshol <larsga at ifi.uio.no> writes:
| 
| I'm translating a numerical algorithm from C to Python, but have run
| into a problem in that the algorithm seems to rely on the fact that
| shifting, addition and multiplication all 'wrap' when the result
| exceeds 32 bits.
| 
| Since the Python equivalents do not, does there exist a common
| workaround for this?
| 
| For example, I'd like
| 
|     mt[0]= seed & 0xffffffff
|     for mti in range(1,n):
|         mt[mti]=(69069 * mt[mti-1]) & 0xffffffff
| 
| to never put anything that doesn't fit in an unsigned long in the mt
| list.

I don't know general ways for wrapping bits, but how about this?

    mt[0] = seed & 0x100000000L
    for mti in range(1, n):
        mt[mti] = (69069L * mt[mti-1]) % 0x100000000L

--
KAJIYAMA, Tamito <kajiyama at grad.sccs.chukyo-u.ac.jp>




More information about the Python-list mailing list