Wise Monks,
I am trying to translate some JS code into Perl. The problem is that I think said JS code does not handle well overflows when doing a left shift and it calculates the result (let's say a checksum) wrongly. But this is now the result and I must emulate that result in my Perl translation. I can not fix the JS code, it is not mine. Question is: how?
Here is the gist of it assuming a 64bit Linux console with node.js installed and bash:
node -e 'console.log(1<<30);' 1073741824 echo $((1<<30)) 1073741824 # same result perl -e 'print 1<<30, "\n"' 1073741824 # same result node -e 'console.log(1<<31);' -2147483648 # overflow in 32bit! echo $((1<<31)) 2147483648 # correct result perl -e 'print 1<<31, "\n"' 2147483648 # same result # to obtain the overflow in bash echo $((1<<63)) -9223372036854775808 # overflow in 64bit # still perl does not perl -e 'print 1<<63, "\n"' 9223372036854775808 perl -e 'print 1<<64, "\n"' 0 # gotcha! # this is when I realised the problem: node -e 'console.log(1169367104<<5);' -1234958336 echo $((1169367104<<5)) 37419747328 perl -e 'print 1169367104<<5, "\n"' 37419747328 # same result
(note: if you don't have node.js open your browser, open its 'web developer tools', go to tab 'console' and just paste that bit of harmless js code
So, I am asking: how can I make perl print -1234958336 when left-shifting 1169367104<<5 ?
use Test::More; is(1169367104<<5, -1234958336, "simulated JS 32bit shift."); done_testing;
bw, bliako
Edit: I have asked a more general question about JS/C/Perl integer overflows at https://stackoverflow.com/questions/77584450/emulate-javascripts-32bit-signed-integer-arithmetic-to-c-or-perl-some-discr
In reply to Trying to translate overflowing JS code to Perl by bliako
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |