Perl unary ~ gives no expected result

I am trying to port a php algorithm to perl, but I am struggling with a single bit operator that I don't know ...

so php code looks like this:

...
$var = '348492634';
print ~$var;
...

result: -348492635

does the same in perl:

...
$var = '348492634';
print ~$var;
...

Result: 18446744073361058981

I read a lot about integer size depending on the processor architecture, but I never found a working solution. Maybe I'm just using the wrong function in perl ...

It is necessary for the logic to get the same result as in the php script.

Thank you in advance

+4
source share
3 answers

It seems that in your installation, PHP ints are 32-bit and perl-int are 64-bit unsigned.

, , , , , , perl.

$var = '348492634'; #hex!
print ~($var - 2**32) - 2**32;
+2

$var='348492634' (, , ), $var=348492634 ( ):

unpack('l', ~pack('l', $var))
+1

Quick and dirty conversion:

print -($var+1);    # like ~$var in PHP

If your perl uses 64-bit integers, this will result in an error only for $var=-18446744073709551616 ( 0x8000000000000000), which in any case will not be used in 32-bit PHP.

0
source

All Articles