py2 vs py3: zlib.adler32/crc32

MRAB python at mrabarnett.plus.com
Thu Nov 14 16:11:37 EST 2019


On 2019-11-14 19:22, Karsten Hilbert wrote:
> Hi all,
> 
> I am unsure how to solve: I use adler32/crc32 to generate integer values from data
> for setting up an advisory lock in PostgreSQL.
> 
> The PG function pg_try_advisory_lock()
> 
>    https://www.postgresql.org/docs/12/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
> 
> takes two PG ints which are defined as:
> 
>     integer 	4 bytes 	typical choice for integer 	-2147483648 to +2147483647
> 
> Now, in Py > 2.5 zlib.adler32/crc32 will return suitable integers.
> 
> However, in Py3 the return range has been changed to
> 
>     The return value is unsigned and in the range [0, 2**32-1] regardless of platform.
> 
> which will overflow the PostgreSQL function.
> 
> Is there a way to convert/modify/shift the py3 value such that it shows the
> same representation as the py2 value ?   What I am looking for is:
> 
>    v2 = py2.zlib.adler32(data)
>    v3 = some_magic(py3.zlib.adler32(data))
>    if v2 == v3:
>       print('same')
> 
> I am sure there's something obvious with struct/<</& and
> such like which I am overlooking.
> 
> Note that I can't simply do
> 
>     v2 = py2.zlib.adler32(data) & 0xffffffff
> 
> because that can overflow the PostgreSQL integer. I think I need
> the reverse, in a sense, but I am too dense, ATM.
> 
Unsigned 32-bit to signed 32-bit:

     unsigned - (unsigned & 0x80000000) * 2

Signed 32-bit to unsigned 32-bit:

     signed & 0xFFFFFFFF


More information about the Python-list mailing list