OK...

{ my $q = $result & 0xFFFF_FFFF ; $result = $q <= 0x7FFF_FFFF ? $q : -1 - ($q ^ 0xFFFF_FFFF) ; } ;
...the objective is to take the LS 32 bits of an integer, 32 bit or more, signed or unsigned, and set $result to be the signed 32 bit integer value. So:

  1. $result & 0xFFFF_FFFF extracts the LS 32 bits and returns an unsigned value.

  2. if the value is now <= 0x7FFF_FFFF, then it's positive, and we're done...

  3. ...otherwise we have 0x8000_0000..0xFFFF_FFFF which we need to map to -0x8000_0000..-0x0000_0001. The XOR $q ^ 0xFFFF_FFFF gives 0x7FFF_FFFF..0x0000_0000, so we complete the process by negating that and subtracting 1... or subtracting that from -1.

    This could also be written -(($q ^ 0xFFFF_FFFF) + 1)or -((~$q + 1) & 0xFFFF_FFFF)... which are closer to the conventional way of changing the sign -- noting that we want this to work for any size of integer from 32 up.

This is assuming 2's complement signed integers. I cannot recall a sign and magnitude machine (for integers). The last 1's complement machine I worked on was a CDC6400 in the 70's. So it's a fairly safe assumption.

But, you could always: unpack('l', pack('L', $result & 0xFFFF_FFFF)), which ensures a valid argument for pack('L', ...) and makes no assumptions about how unpack('l', ...) interprets the bits.


In reply to Re^4: Integer overflow by gone2015
in thread Integer overflow by terranullis

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.