in reply to Perl's bad at arithmetic?

Yeah, that's certainly surprising. But when I looked in the docs (perldoc perlop) it says that:

Note that both << and >> in Perl are implemented directly using << and >> in C. If use integer (see Integer Arithmetic) is in force then signed C integers are used, else unsigned C integers are used. Either way, the implementation isn't going to generate results larger than the size of the integer type Perl was built with (32 bits or 64 bits).

The result of overflowing the range of the integers is undefined because it is undefined also in C. In other words, using 32-bit integers, 1 << 32 is undefined. Shifting by a negative number of bits is also undefined.

If you get tired of being subject to your platform's native integers, the use bigint pragma neatly sidesteps the issue altogether:

I was expecting that the 1 would shift off the end and leave you with all 0, rather than it wrapping back around.

...roboticus

When your only tool is a hammer, all problems look like your thumb.

Replies are listed 'Best First'.
Re^2: Perl's bad at arithmetic?
by BrowserUk (Patriarch) on Mar 27, 2015 at 23:39 UTC

    Forget the shifts, look at the numbers: They should be 19, 36 & 69. (And on a 64-bit machine the first 2 should be fine for shifting a 64-bit int.)


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
    In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked

      BrowserUk:

      But the numbers look right (though backwards from the way I expect to see 'em). If you shift your 1 nineteen positions over and subtract one from the result, you'd get what you're showing you'd get. I don't see the issue with the first two.

      The last one, however looks like it rotated the 1 bit one end and onto the other.

      ...roboticus

      When your only tool is a hammer, all problems look like your thumb.

        You're right of course. (Too late at night! )

        I was ignoring the shift; and expecting to see 19 (not 2**19 -1). I knew I was wrong but ... It's been a looooooooooooong day.


        With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
        In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked