in reply to Re^2: Trying to translate overflowing JS code to Perl
in thread Trying to translate overflowing JS code to Perl

I believe you can do the complete calculation without conversion and just at the end downgrade to 32 bit and convert to signed. The following should work:

sub calc_32bit_signed( $value ) { return unpack( "l", pack "L", ($value & 0xffffffff))) } ... say calc_32bit_signed( $n << 6 ); say calc_32bit_signed( $n + 2 );

Replies are listed 'Best First'.
Re^4: Trying to translate overflowing JS code to Perl
by syphilis (Archbishop) on Nov 29, 2023 at 11:42 UTC
    return unpack( "l", pack "L", ($value & 0xffffffff)))

    For which finite numeric values do any of the following 3 renditions differ:
    say unpack( "l", pack "L", ($value & 0xffffffff)); say unpack( "l", pack "L", ($value)); say unpack( "l", pack "l", ($value));
    Sorry ... I'm not trying to be critical ... not even nitpicking ... but I haven't found any such values, and I'm genuinely curious as to whether they exist.)

    Cheers,
    Rob

      Yeah - I wasn't sure either. Reconsidering, I think pack "L" and pack "l" both truncate the value to 32 bits already, so masking out higher bits does not make a difference.

Re^4: Trying to translate overflowing JS code to Perl
by bliako (Abbot) on Nov 30, 2023 at 18:00 UTC

    I don't think that will work, for example consider something like ($value << 6) + length($value). So if the first part overflows in JS then it is necessary to overflow (the first part) in Perl too. Simulating the overflow for the sum would not do. At the moment I am running JS code via shelling out to node.js and that works just fine.

    I was hoping that there would be a module like Math::BigInt where you specify the number of bits or something like use smallint; But now, come to think of it, perhaps a new module could consist of only overloading arithmetic operators. Let me see if I can whip up something based on your pack receipe.

    Edit: see Re: Trying to translate overflowing JS code to Perl with working code for this.